Exemplo n.º 1
0
        public ActionResult SlackCallback(string code)
        {
            var siteSettings = _settingsService.GetSiteSettings();
            var slackService = new SlackService(siteSettings.SlackSettings);

            var oauthToken  = slackService.ExchangeCodeForToken(code);
            var slackExists = _linkedAccountRepository.GetBy(l => l.AccountType == LinkedAccountType.Slack && l.UserId == WebUser.Id);

            if (slackExists != null)
            {
                slackExists.AccessToken = oauthToken.access_token;
                slackExists.Scope       = oauthToken.scope;
                _linkedAccountRepository.Update(slackExists);
                _unitOfWork.Commit();
            }
            else
            {
                var linkedAccount = new LinkedAccount
                {
                    AccountType = LinkedAccountType.Slack,
                    UserId      = WebUser.Id,
                    AccessToken = oauthToken.access_token,
                    Scope       = oauthToken.scope
                };

                _linkedAccountRepository.Create(linkedAccount);
                _unitOfWork.Commit();
            }

            return(RedirectToAction("Index"));
        }
        protected override void ProcessHTML()
        {
            if (HtmlDoc != null && HtmlDoc.HasData)
            {
                string firstItem = string.Empty;
                List <LinkedAccount>        items      = new List <LinkedAccount>();
                List <ParseDataItem>        components = null;
                IEnumerable <ParseDataItem> htmlItems  = HtmlDoc.Items.Where(x => !x.Header.ToUpper().Contains("DEFINITION"));
                IEnumerable <ParseDataItem> toSearch   = htmlItems.Count() > 1 ? htmlItems : htmlItems.ElementAt(0).Children;
                //IEnumerable<ParseDataItem> toSearch = HtmlDoc.Items.Count() > 1 ? HtmlDoc.Items : HtmlDoc.Items.ElementAt(0).Children;
                if (toSearch != null && toSearch.Any())
                {
                    if (toSearch != null && toSearch.Any())
                    {
                        foreach (ParseDataItem item in toSearch)
                        {
                            if (string.IsNullOrEmpty(firstItem))
                            {
                                firstItem = item.Header;
                            }

                            if (item.Header.Equals(firstItem) && components != null && components.Any())
                            {
                                LinkedAccount newItem = new LinkedAccount(Logger, DisplaySectionName, components);
                                if (newItem.HasData)
                                {
                                    items.Add(newItem);
                                }
                                components = null;
                            }
                            if (components == null)
                            {
                                components = new List <ParseDataItem>();
                            }
                            components.Add(item);
                        }

                        if (components != null && components.Any())
                        {
                            LinkedAccount newItem = new LinkedAccount(Logger, DisplaySectionName, components);
                            if (newItem.HasData)
                            {
                                items.Add(newItem);
                            }
                        }
                    }
                    if (items.Count == 0)
                    {
                        throw new SectionEmptyException(DisplaySectionName);
                    }

                    Items = items;
                }
            }

            if (!HasData)
            {
                throw new SectionEmptyException(DisplaySectionName);
            }
        }
Exemplo n.º 3
0
        public ActionResult LinkedInCallback(string code, string state)
        {
            var linkedInService = new LinkedInService("81ed9a1o1frnfw", "1LhWRlz3ZCWxSjyF");
            var urlHelper       = new UrlHelper(ControllerContext.RequestContext);
            var callbackUrl     = urlHelper.Action("LinkedInCallback", "Profile", null, "http");

            state = Session["linkedin_state"].ToString();
            var oauthToken = linkedInService.ExchangeCodeForToken(code, state, callbackUrl);

            var linkedInExists = _linkedAccountRepository.GetBy(l => l.AccountType == LinkedAccountType.LinkedIn && l.UserId == WebUser.Id);

            if (linkedInExists != null)
            {
                linkedInExists.AccessToken = oauthToken.access_token;
                linkedInExists.Scope       = oauthToken.scope;
                _linkedAccountRepository.Update(linkedInExists);
                _unitOfWork.Commit();
            }
            else
            {
                var linkedAccount = new LinkedAccount
                {
                    AccountType = LinkedAccountType.LinkedIn,
                    UserId      = WebUser.Id,
                    AccessToken = oauthToken.access_token,
                    Scope       = oauthToken.scope
                };

                _linkedAccountRepository.Create(linkedAccount);
                _unitOfWork.Commit();
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "disconnect")]
            HttpRequest request,
            [Table("LinkedAccounts")] CloudTable table,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            (ClaimsPrincipal user, SecurityToken _) = await _auth0Authenticator.AuthenticateAsync(request, logger, cancellationToken);

            string userId = _auth0Authenticator.GetUserId(user);

            logger.LogInformation($"User authenticated, user id='{userId}'");

            try
            {
                LinkedAccount linkedAccount = await _linkedAccountService.GetLinkedAccountAsync(userId, table, logger);

                // De-authorize Strava account
                await DeauthorizeAsync(linkedAccount, logger, cancellationToken);

                // Delete linked account from table storage
                TableOperation operation = TableOperation.Delete(linkedAccount);
                await table.ExecuteAsync(operation);

                // todo: delete workout files from blob storage
                return(new OkResult());
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error occurred while trying to unlink Strava account");
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }
        }
Exemplo n.º 5
0
 public static void Evaluate(LinkedAccount account)
 {
     if (account.Directory.Account.Mail != account.Directory.Account.PrincipalName)
     {
         account.Actions.Add(new PrincipalNameMustEqualMail());
         account.Directory.FlagWarning();
         account.OK = false;
     }
 }
 protected override void RemoveLinkedAccount(LinkedAccount item)
 {
     var removed =
         this.LinkedAccountsCollection.SingleOrDefault(
             x =>
             x.ProviderAccountID == item.ProviderAccountID && x.ProviderName == item.ProviderName
             && x.LastLogin == item.LastLogin);
     this.LinkedAccountsCollection.Remove(removed);
 }
 protected override void AddLinkedAccount(LinkedAccount item)
 {
     var linkedAccount = new NhLinkedAccount();
     linkedAccount.GetType().GetProperty("LastLogin").SetValue(linkedAccount, item.LastLogin);
     linkedAccount.GetType().GetProperty("ProviderAccountID").SetValue(linkedAccount, item.ProviderAccountID);
     linkedAccount.GetType().GetProperty("ProviderName").SetValue(linkedAccount, item.ProviderName);
     linkedAccount.GetType().GetProperty("Account").SetValue(linkedAccount, this);
     this.LinkedAccountsCollection.Add(linkedAccount);
 }
 public static void Evaluate(LinkedAccount account)
 {
     if (!account.Smartschool.Account.BirthPlace.Equals(account.Wisa.Account.PlaceOfBirth, StringComparison.CurrentCulture))
     {
         account.Smartschool.FlagWarning();
         account.Actions.Add(new ModifySmartschoolBirthPlace());
         account.OK = false;
     }
 }
Exemplo n.º 9
0
        protected override void AddLinkedAccount(LinkedAccount item)
        {
            var linkedAccount = new NhLinkedAccount();

            linkedAccount.GetType().GetProperty("LastLogin").SetValue(linkedAccount, item.LastLogin);
            linkedAccount.GetType().GetProperty("ProviderAccountID").SetValue(linkedAccount, item.ProviderAccountID);
            linkedAccount.GetType().GetProperty("ProviderName").SetValue(linkedAccount, item.ProviderName);
            linkedAccount.GetType().GetProperty("Account").SetValue(linkedAccount, this);
            this.LinkedAccountsCollection.Add(linkedAccount);
        }
Exemplo n.º 10
0
        protected override void RemoveLinkedAccount(LinkedAccount item)
        {
            var removed =
                this.LinkedAccountsCollection.SingleOrDefault(
                    x =>
                    x.ProviderAccountID == item.ProviderAccountID && x.ProviderName == item.ProviderName &&
                    x.LastLogin == item.LastLogin);

            this.LinkedAccountsCollection.Remove(removed);
        }
Exemplo n.º 11
0
        public async override Task Apply(LinkedAccount account, DateTime deletionDate)
        {
            bool connected = await State.App.Instance.AD.Connect().ConfigureAwait(false);

            if (!connected)
            {
                return;
            }

            account.Directory.Account.PrincipalName = account.Directory.Account.Mail;
        }
        public ActionResult DeleteConfirmed(int id)
        {
            int loggedUser = (int)Session["id"];

            id = db.LinkedAccounts.Where(x => ((x.Account1ID == id && x.Account2ID == loggedUser) ||
                                               (x.Account1ID == loggedUser && x.Account2ID == id))).Select(x => x.ID).First();
            LinkedAccount linkedAccount = db.LinkedAccounts.Find(id);

            db.LinkedAccounts.Remove(linkedAccount);
            db.SaveChanges();
            return(RedirectToAction("Details2", "Users", new { id = (int)Session["id"] }));
        }
Exemplo n.º 13
0
        private async Task <string> GetValidStravaAccessTokenAsync(LinkedAccount linkedAccount, CloudTable table, ILogger logger, CancellationToken cancellationToken)
        {
            if (linkedAccount.ExpiresAt > DateTime.Now)
            {
                return(linkedAccount.AccessToken);
            }

            try
            {
                logger.LogInformation($"Access token expired at '{linkedAccount.ExpiresAt}', trying to refresh...");

                RefreshTokenModel refreshTokenModel = new RefreshTokenModel()
                {
                    ClientId     = _configuration["Strava:ClientId"],
                    ClientSecret = _configuration["Strava:ClientSecret"],
                    RefreshToken = linkedAccount.RefreshToken
                };
                var json = JsonConvert.SerializeObject(refreshTokenModel);

                HttpResponseMessage response = await _httpClient.PostAsync(new Uri("https://www.strava.com/api/v3/oauth/token"), new StringContent(json, Encoding.UTF8, "application/json"), cancellationToken);

                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();

                logger.LogInformation($"Received token response from Strava: '{responseBody}'");

                AccessTokenModel accessTokenModel = JsonConvert.DeserializeObject <AccessTokenModel>(responseBody);
                logger.LogInformation($"Parsed Access token: '{accessTokenModel.AccessToken}', expires at '{accessTokenModel.ExpiresAt}'");

                // Update tokens in the table storage
                logger.LogInformation($"Saving access token for user: '******' '{linkedAccount.IdpUserName}'. Strava user:'******' {linkedAccount.FirstName} {linkedAccount.LastName}");
                linkedAccount.TokenType    = accessTokenModel.TokenType;
                linkedAccount.AccessToken  = accessTokenModel.AccessToken;
                linkedAccount.ExpiresAt    = accessTokenModel.ExpiresAt;
                linkedAccount.RefreshToken = accessTokenModel.RefreshToken;

                TableOperation operation = TableOperation.Merge(linkedAccount);
                await table.ExecuteAsync(operation);

                return(accessTokenModel.AccessToken);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error occurred while requesting athlete info from Strava");
                return(null);
            }
        }
Exemplo n.º 14
0
        private async Task DeauthorizeAsync(LinkedAccount linkedAccount, ILogger logger, CancellationToken cancellationToken)
        {
            logger.LogInformation($"Calling deauthorize endpoint for user: '******' '{linkedAccount.IdpUserName}'. Strava user:'******' {linkedAccount.FirstName} {linkedAccount.LastName}");

            var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://www.strava.com/oauth/deauthorize"));

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", linkedAccount.AccessToken);

            HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken);

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();

            logger.LogInformation($"Received token response from Strava: '{responseBody}'");
        }
Exemplo n.º 15
0
        public async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "connect")]
            [FromBody] Shared.Models.ConnectStravaApp connectStravaApp,
            HttpRequest request,
            [Table("LinkedAccounts")] CloudTable table,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            (ClaimsPrincipal user, SecurityToken _) = await _auth0Authenticator.AuthenticateAsync(request, logger, cancellationToken);

            string userId = _auth0Authenticator.GetUserId(user);

            logger.LogInformation($"User authenticated, user id='{userId}'");

            // Hit the auth0 user_info API and see what we get back about this user
            var           authorizationHeader = AuthenticationHeaderValue.Parse(request.Headers["Authorization"]);
            Auth0UserInfo userInfo            = await GetAuth0UserinfoAsync(authorizationHeader, logger, cancellationToken);

            logger.LogInformation($"Got user info from auth0: '{userInfo}'");

            AccessTokenModel stravaAccessToken = await PerformCodeExchangeAsync(connectStravaApp.AuthorizationCode, userInfo, logger, cancellationToken);

            // Save token in the table storage
            LinkedAccount linkedAccount = new LinkedAccount()
            {
                IdpUserId       = userInfo.UserId,
                IdpUserName     = userInfo.Name,
                StravaAccountId = stravaAccessToken.Athlete.Id,
                FirstName       = stravaAccessToken.Athlete.FirstName,
                LastName        = stravaAccessToken.Athlete.LastName,
                Profile         = stravaAccessToken.Athlete.Profile,
                TokenType       = stravaAccessToken.TokenType,
                AccessToken     = stravaAccessToken.AccessToken,
                ExpiresAt       = stravaAccessToken.ExpiresAt,
                RefreshToken    = stravaAccessToken.RefreshToken,
            };

            logger.LogInformation($"Saving access token for user: '******' '{linkedAccount.IdpUserName}'. Strava user:'******' {linkedAccount.FirstName} {linkedAccount.LastName}");
            linkedAccount.PartitionKey = Constants.LinkedAccountPartitionKey;
            linkedAccount.RowKey       = linkedAccount.IdpUserId;
            linkedAccount.ETag         = "*";

            TableOperation operation = TableOperation.InsertOrMerge(linkedAccount);
            await table.ExecuteAsync(operation);

            return(new OkResult());
        }
Exemplo n.º 16
0
        public override FlowDocument GetDetails(LinkedAccount account)
        {
            var result = new FlowTableCreator(true);

            result.SetHeaders(new string[] { "Active Directory", "Smartschool" });

            result.AddRow(new List <string>()
            {
                "Email", account.Directory.Account.PrincipalName, account.Smartschool.Account.Mail
            });

            FlowDocument document = new FlowDocument();

            document.Blocks.Add(result.Create());

            return(document);
        }
Exemplo n.º 17
0
        public async Task <LinkedAccount> GetLinkedAccountAsync(string userId, CloudTable table, ILogger logger)
        {
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <LinkedAccount>(Constants.LinkedAccountPartitionKey, userId);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                LinkedAccount linkedAccount = result.Result as LinkedAccount;

                return(linkedAccount);
            }
            catch (StorageException ex)
            {
                logger.LogError(ex, "Cannot read linked account from the table storage");
                return(null);
            }
        }
        // GET: LinkedAccounts/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            int loggedUser = (int)Session["id"];

            id = db.LinkedAccounts.Where(x => ((x.Account1ID == id && x.Account2ID == loggedUser) ||
                                               (x.Account1ID == loggedUser && x.Account2ID == id))).Select(x => x.ID).First();
            LinkedAccount linkedAccount = db.LinkedAccounts.Find(id);

            if (linkedAccount == null)
            {
                return(HttpNotFound());
            }
            return(View(linkedAccount));
        }
Exemplo n.º 19
0
        public async Task LinkAccount(string linkedService, string link)
        {
            if (supportedLinks.Any(x => x.Equals(linkedService, StringComparison.OrdinalIgnoreCase)))
            {
                LinkedAccount acc = new LinkedAccount
                {
                    User = await _database.UserData.FirstOrDefaultAsync(usr => usr.UserId == Context.User.Id),
                    LinkedServiceLink = link,
                    Type = linkedService
                };
            }
            else
            {
                await ReplyAsync("This service is not supported for linking");

                return;
            }
        }
Exemplo n.º 20
0
        public ActionResult LinkAccount(User model)
        {
            /*
             * This will check if the username is in the database while also retrieving the password asociated with the user.
             * If the user isn't in the database, then the query returns null which is handled by the ??. If a result is null
             * The the var password is assigned whatever is put on the right side of ??
             */
            string password = db.Users.Where(x => x.Username == model.Username.ToString()).Select(x => x.Password).FirstOrDefault() ?? "NoUser";

            if (password != model.Password.ToString() || password == "NoUser")
            {
                ModelState.AddModelError(string.Empty, "Incorrect user name or password");
                return(View(model));
            }
            else
            {
                int  userId = (int)(from x in db.Users where x.Username == model.Username.ToString() select x.ID).SingleOrDefault();
                User user   = db.Users.Find(userId);
                //Check if trying to link to yourself
                int loggedInId = (int)Session["id"];
                if (user.ID == loggedInId)
                {
                    ModelState.AddModelError(string.Empty, "Cannot link to yourself");
                    return(View(model));
                }

                //Check if this other account is already linked to be sure
                if (db.LinkedAccounts.Where(x => x.Account1ID == user.ID || x.Account2ID == user.ID).Count() == 0)
                {
                    LinkedAccount newLink = new LinkedAccount();
                    newLink.Account1ID = (int)Session["id"];
                    newLink.Account2ID = userId;
                    db.LinkedAccounts.Add(newLink);
                    db.SaveChanges();
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "That Account is already linked");
                    return(View(model));
                }

                return(RedirectToAction("Details2", "Users", new { id = (int)Session["id"] }));
            }
        }
Exemplo n.º 21
0
        public override FlowDocument GetDetails(LinkedAccount account)
        {
            var result = new FlowTableCreator(false);

            result.SetHeaders(new string[] { "Veld", "Waarde" });
            result.AddRow(new List <string>()
            {
                "Mail", account.Directory.Account.Mail
            });
            result.AddRow(new List <string>()
            {
                "UserPrincipalName", account.Directory.Account.PrincipalName
            });

            FlowDocument document = new FlowDocument();

            document.Blocks.Add(result.Create());

            return(document);
        }
Exemplo n.º 22
0
        private async Task <AthleteModel> GetAthleteAsync(string token, LinkedAccount linkedAccount, CloudTable table, ILogger logger, CancellationToken cancellationToken)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://www.strava.com/api/v3/athlete"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

                HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken);

                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();

                logger.LogInformation($"Received response from Strava: '{responseBody}'");

                AthleteModel athleteModel = JsonConvert.DeserializeObject <AthleteModel>(responseBody);

                // Update linked account in the table storage if the user profile changed
                if (linkedAccount.StravaAccountId != athleteModel.Id ||
                    linkedAccount.FirstName != athleteModel.FirstName ||
                    linkedAccount.LastName != athleteModel.LastName)
                {
                    logger.LogInformation($"Updating Strava account for user: '******' '{linkedAccount.IdpUserName}'. Strava user:'******' {linkedAccount.FirstName} {linkedAccount.LastName}");
                    linkedAccount.StravaAccountId = athleteModel.Id;
                    linkedAccount.FirstName       = athleteModel.FirstName;
                    linkedAccount.LastName        = athleteModel.LastName;

                    TableOperation operation = TableOperation.Merge(linkedAccount);
                    await table.ExecuteAsync(operation);
                }

                return(athleteModel);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error occurred while requesting athlete info from Strava");
                return(null);
            }
        }
Exemplo n.º 23
0
        protected override OpResult _Store(LinkedAccount _obj)
        {
            if (_obj == null)
            {
                return(OpResult.NotifyStoreAction(OpResult.ResultStatus.ObjectIsNull, _obj, "LinkedAccount object cannot be created as it is null"));
            }

            if (Exists(_obj))
            {
                ExecuteNonQuery(GetQuery_UpdateQuery(_obj));
                return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Updated, _obj));
            }

            ExecuteNonQuery(GetQuery_InsertQuery(_obj));
            if (_obj.LinkedAccountID == null)
            {
                _obj.LinkedAccountID = DbMgr.GetLastInsertID();
            }
            _obj.FromDb = true;

            return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Created, _obj));
        }
Exemplo n.º 24
0
        private async Task <AthleteStatsModel> GetAthleteStatsAsync(string token, LinkedAccount linkedAccount, ILogger logger, CancellationToken cancellationToken)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://" + $"www.strava.com/api/v3/athletes/{linkedAccount.StravaAccountId}/stats"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

                HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken);

                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();

                logger.LogInformation($"Received response from Strava: '{responseBody}'");

                AthleteStatsModel statsModel = JsonConvert.DeserializeObject <AthleteStatsModel>(responseBody);
                return(statsModel);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error occurred while requesting athlete info from Strava");
                return(null);
            }
        }
Exemplo n.º 25
0
 protected internal override void RemoveLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Remove((TLinkedAccount)item);
 }
Exemplo n.º 26
0
 protected internal override void AddLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Add(item);
 }
Exemplo n.º 27
0
 protected internal override void AddLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Add(new TLinkedAccount {
         ParentKey = this.Key, ProviderName = item.ProviderName, ProviderAccountID = item.ProviderAccountID, LastLogin = item.LastLogin
     });
 }
 public async override Task Apply(LinkedAccount linkedAccount, DateTime deletionDate)
 {
     linkedAccount.Smartschool.Account.BirthPlace = linkedAccount.Wisa.Account.PlaceOfBirth;
     await AccountApi.Smartschool.AccountManager.Save(linkedAccount.Smartschool.Account, "").ConfigureAwait(false);
 }
 protected internal override void AddLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Add(new RelationalLinkedAccount { UserAccountID = this.ID, ProviderName = item.ProviderName, ProviderAccountID = item.ProviderAccountID, LastLogin = item.LastLogin });
 }
Exemplo n.º 30
0
        // GET: Users/Details/5
        public ActionResult Details2(int?id, string sortOrder, string currentFilter, int?page, string postAndOrUsername)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UserAndPosts user = new UserAndPosts();

            user.user  = db.Users.Find(id);
            user.posts = (from x in db.UserPosts where x.User_ID == id select x).ToList();

            /*
             * There are several situations when it comes to being able to follow
             * and see if you are already following. We also have to consider whether
             * a user is viewing their own page in which case the option to follow
             * or unfollow shouldn't appear as a user can't follow themseves
             */

            //No one is logged in or user is viewing themselves
            if (Session["username"] == null ||
                Session["username"].ToString() == user.user.Username)
            {
                user.following = "invalid";
                if (Session["username"] == null || Session["username"].ToString() == user.user.Username)
                {
                    if (db.LinkedAccounts.Where(x => x.Account1ID == id || x.Account2ID == id).Count() > 0)
                    {
                        LinkedAccount link = db.LinkedAccounts.Where(x => x.Account1ID == id || x.Account2ID == id).Single();
                        if (link.Account1ID == id)
                        {
                            user.otherAccount = db.Users.Find(link.Account2ID);
                        }
                        else
                        {
                            user.otherAccount = db.Users.Find(link.Account1ID);
                        }
                    }
                }
            }
            //User is viewing another profile and is logged in
            else
            {
                int sessionID = (int)Session["id"];
                //int followingint = db.FollowLists.Where(x => (x.FolloweeID == id) && (x.FollowerID == sessionID)).Select(x => x.ID);

                if ((db.FollowLists.Where(x => (x.FolloweeID == id) && (x.FollowerID == sessionID)).Select(x => x.ID)).FirstOrDefault() != 0)
                {
                    //There is a following between current user and profile of the user they are on,
                    //meaning they should get the option to unfollow
                    user.following = "Unfollow";
                }
                else
                {
                    //They are not following the user profile they are currently on.
                    //meaning they should get the option to follow
                    user.following = "Follow";
                }
                user.otherAccount = null;
            }

            //Sorting the Table
            ViewBag.CurrentSort = sortOrder;
            List <string> list = new List <string>();

            list.Add("Post Title");
            list.Add("Username");
            list.Add("Both");
            ViewBag.PostAndOrUsername         = new SelectList(list);
            ViewBag.SelectedPostAndOrUsername = postAndOrUsername;
            ViewBag.DateSortParm     = String.IsNullOrEmpty(sortOrder) ? "date_asc" : "";
            ViewBag.TitleSortParm    = sortOrder == "Title" ? "title_desc" : "Title";
            ViewBag.LikesSortParm    = sortOrder == "Likes" ? "likes_desc" : "Likes";
            ViewBag.DislikesSortParm = sortOrder == "Dislikes" ? "dislikes_desc" : "Dislikes";
            ViewBag.UserNameSortParm = sortOrder == "UserName" ? "userName_desc" : "UserName";
            page = 1;
            switch (sortOrder)
            {
            case "date_asc":
                user.posts = user.posts.OrderBy(p => p.Date_Posted);
                break;

            case "title_desc":
                user.posts = user.posts.OrderByDescending(p => p.Title);
                break;

            case "Title":
                user.posts = user.posts.OrderBy(p => p.Title);
                break;

            case "likes_desc":
                user.posts = user.posts.OrderByDescending(p => p.Likes);
                break;

            case "Likes":
                user.posts = user.posts.OrderBy(p => p.Likes);
                break;

            case "dislikes_desc":
                user.posts = user.posts.OrderByDescending(p => p.Dislikes);
                break;

            case "Dislikes":
                user.posts = user.posts.OrderBy(p => p.Dislikes);
                break;

            default:
                user.posts = user.posts.OrderByDescending(p => p.Date_Posted);
                break;
            }
            //End of sorting the Table

            /* USE FOR PAGING THE TABLE
             * int pageSize = 3;
             * int pageNumber = (page ?? 1);
             */
            return(View(user));
        }
Exemplo n.º 31
0
 private DbUpdateStatement GetQuery_UpdateQuery(LinkedAccount _obj)
 {
     return(DbMgr.CreateUpdateClause("LinkedAccounts", GetFields(_obj), "LinkedAccountID", _obj.LinkedAccountID));
 }
 protected internal override void RemoveLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Remove((RelationalLinkedAccountInt)item);
 }
Exemplo n.º 33
0
        public async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "userinfo")]
            HttpRequest request,
            [Table("LinkedAccounts")] CloudTable table,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            try
            {
                // The "user" returned here is an actual ClaimsPrincipal with the claims that were in the access_token.
                // The "token" is a SecurityToken that can be used to invoke services on the part of the user. E.g., create a Google Calendar event on the user's calendar.
                (ClaimsPrincipal user, SecurityToken token) = await _auth0Authenticator.AuthenticateAsync(request, logger, cancellationToken);

                string userId = _auth0Authenticator.GetUserId(user);
                logger.LogInformation($"User authenticated, user id='{userId}'");

                UserInfoModel userInfo = new UserInfoModel();

                LinkedAccount linkedAccount = await _linkedAccountService.GetLinkedAccountAsync(userId, table, logger);

                if (linkedAccount != null)
                {
                    // validate that the access token has not expired and renew if needed
                    string accessToken = await GetValidStravaAccessTokenAsync(linkedAccount, table, logger, cancellationToken);

                    if (accessToken != null)
                    {
                        AthleteModel athlete = await GetAthleteAsync(accessToken, linkedAccount, table, logger, cancellationToken);

                        if (athlete != null)
                        {
                            logger.LogInformation($"Got athlete info from Strava: '{athlete}'");

                            userInfo.FirstName  = athlete.FirstName;
                            userInfo.LastName   = athlete.LastName;
                            userInfo.Country    = athlete.Country;
                            userInfo.City       = athlete.City;
                            userInfo.PictureUrl = athlete.Profile;

                            userInfo.IsStravaAccountLinked = true;
                        }

                        AthleteStatsModel stats = await GetAthleteStatsAsync(accessToken, linkedAccount, logger, cancellationToken);

                        if (stats != null)
                        {
                            logger.LogInformation($"Got athlete stats from Strava: '{stats}'");

                            userInfo.Runs  = stats.AllRunsTotals.Count;
                            userInfo.Swims = stats.AllSwimsTotals.Count;
                            userInfo.Rides = stats.AllRidesTotals.Count;
                        }
                    }
                }

                return(new OkObjectResult(userInfo));
            }
            catch (AuthException)
            {
                return(new UnauthorizedResult());
            }
        }
 protected internal override void AddLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Add(new RelationalLinkedAccount {
         UserAccountID = this.ID, ProviderName = item.ProviderName, ProviderAccountID = item.ProviderAccountID, LastLogin = item.LastLogin
     });
 }
 protected internal override void RemoveLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Remove(item);
 }
 protected internal override void AddLinkedAccount(LinkedAccount item)
 {
     LinkedAccountCollection.Add(item);
 }