Beispiel #1
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            byte[] instagramUserCookies = null;

            bool authenticated = _instagramAPI.TryAuthenticate(model.Username, model.Password, out instagramUserCookies);

            if (authenticated)
            {
                var    newUser    = new ApplicationUser();
                string primaryKey = _instagramAPI.GetCurrentUserPrimaryKey();

                if (string.IsNullOrEmpty(primaryKey))
                {
                    ModelState.AddModelError("", "Authentication error. Try later.");
                    return(View(model));
                }

                newUser.InstagramPK = primaryKey;
                newUser.StateData   = instagramUserCookies;
                newUser.Username    = model.Username;

                var foundUser = await _repository.GetAsync <ApplicationUser>(u => u.InstagramPK == primaryKey);

                if (foundUser == null)
                {
                    newUser.Subscriptions  = _instagramAPI.GetUserSubscriptionsByUsername(model.Username);
                    newUser.LastUpdateDate = DateTime.Now;
                    await _repository.CreateAsync <ApplicationUser>(newUser);
                }
                else
                {
                    foundUser.StateData = instagramUserCookies;
                    //Maybe user has been changed his username after last authorization
                    foundUser.Username = model.Username;
                    await _repository.UpdateAsync <ApplicationUser>(foundUser);
                }

                Session["PrimaryKey"] = primaryKey;
                Session["Authorized"] = true;
                Session["UserName"]   = model.Username;

                return(RedirectToLocal(returnUrl));
            }
            else
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }