コード例 #1
0
        public new ActionResult Profile()
        {
            BundleConfig.RegisterProfileBundles(BundleTable.Bundles);

            ProfileViewModel viewModel = null;

            try
            {
                string      userId      = User.Identity.GetUserId();
                string      userName    = User.Identity.GetUserName();
                PhiUser     currentUser = _userStore.FindByNameAsync(userName).Result;
                UserProfile profile     = _userProfileStore.GetUserProfileById(userId);

                if (currentUser != null)
                {
                    if (profile == null)
                    {
                        this._userProfileStore.Insert(new UserProfile
                        {
                            PhiUserId = currentUser.Id,
                            NotifyMeAboutSuddenWeatherEvents = true // True by default
                        });

                        profile = _userProfileStore.GetUserProfileById(User.Identity.GetUserId());
                    }

                    var location = _GetLocationDescription(profile.LocationId);

                    viewModel = new ProfileViewModel
                    {
                        FirstName         = currentUser.FirstName,
                        LastName          = currentUser.LastName,
                        UserName          = currentUser.UserName,
                        DateCreated       = currentUser.DateCreated,
                        Email             = currentUser.Email,
                        Gender            = profile.Gender,
                        AvatarPictureUrl  = profile.AvatarPictureUrl,
                        Location          = location,
                        IsCheckedLocation = false
                    };
                    _GatherStatistics(userId, currentUser.UserName, currentUser.Email, "Profile");
                }
                else
                {
                    _GatherStatistics(userId, userName, null, "Profile");
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Exception HttpGet Profile", ex);
            }

            if (viewModel != null)
            {
                return(View(viewModel));
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #2
0
        public static async Task <ClaimsIdentity> GenerateUserIdentityAsync(PhiUser user, UserManager <PhiUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            return(userIdentity);
        }
コード例 #3
0
 private async Task SignInAsync(PhiUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties()
     {
         IsPersistent = isPersistent
     }, await PhiUserHelpers.GenerateUserIdentityAsync(user, UserManager));
 }
コード例 #4
0
        public async Task <ActionResult> ConfirmEmail(string userId, string code)
        {
            if (userId == null || code == null)
            {
                return(View("Error"));
            }
            MyIdentityResult result;

            try
            {
                result = await UserManager.ConfirmEmailAsync(userId, code);
            }
            catch (InvalidOperationException ioe)
            {
                _logger.Error("Exception ConfirmEmail userId:" + userId + ", code: " + code, ioe);

                // ConfirmEmailAsync throws when the userId is not found.
                ViewBag.errorMessage = ioe.Message;
                return(View("Error"));
            }

            if (result.IsSucceeded)
            {
                PhiUser user = await UserManager.FindByIdAsync(userId);

                await _emailStore.SetEmailConfirmedAsync(user, true);

                // Create profile by default.
                UserProfile profile = _userProfileStore.GetUserProfileById(userId);

                if (profile == null)
                {
                    this._userProfileStore.Insert(new UserProfile
                    {
                        PhiUserId = userId,
                        NotifyMeAboutSuddenWeatherEvents = true // True by default
                    });
                }

                return(RedirectToLocal("/Account/Authorize?client_id=web&response_type=token&state="));
            }

            // If we got this far, something failed.
            AddErrors(result);
            ViewBag.errorMessage = GlobalResources.ConfirmEmailFailed;
            return(View("Error"));
        }
コード例 #5
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new PhiUser()
                {
                    UserName = model.Email, Email = model.Email, DateCreated = DateTime.UtcNow
                };
                IdentityResult result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent : false);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.LoginProvider = string.Empty;
            ViewBag.ReturnUrl     = returnUrl;
            return(View(model));
        }
コード例 #6
0
        /// <summary>
        /// Gets a value indicating whether user is in a certain user role
        /// </summary>
        /// <param name="user">PhiUser</param>
        /// <param name="userRoleSystemName">PhiUser role system name</param>
        /// <returns>Result</returns>
        public static bool IsInUserRole(this PhiUser user, string userRoleSystemName)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (String.IsNullOrEmpty(userRoleSystemName))
            {
                throw new ArgumentNullException("userRoleSystemName");
            }

            var result = user.UserRoles
                         .Where(cr => cr.Role.Active)
                         .Where(cr => cr.Role.Name == userRoleSystemName)
                         .FirstOrDefault() != null;

            return(result);
        }
コード例 #7
0
        public ActionResult AdvancedProfile()
        {
            BundleConfig.RegisterProfileBundles(BundleTable.Bundles);

            try
            {
                string      userId      = User.Identity.GetUserId();
                string      userName    = User.Identity.GetUserName();
                PhiUser     currentUser = _userStore.FindByNameAsync(userName).Result;
                UserProfile profile     = _userProfileStore.GetUserProfileById(userId);

                if (currentUser != null)
                {
                    return(View(new AdvancedProfileViewModel
                    {
                        CompanyName = profile.CompanyName,
                        CompanyCEO = profile.CompanyCEO,
                        CompanyEmail = profile.CompanyEmail,
                        CompanyFax = profile.CompanyFax,
                        CompanyPhone = profile.CompanyPhone,
                        MainCompanyUrl = profile.MainCompanyUrl,
                        SellCompanyUrl = profile.SellCompanyUrl,
                        AdditionalInfo = profile.AdditionalInfo,
                        NotifyAboutWeatherEvents = profile.NotifyMeAboutSuddenWeatherEvents
                    }));

                    _GatherStatistics(userId, currentUser.UserName, currentUser.Email, "AdvancedProfile");
                }
                else
                {
                    _GatherStatistics(userId, userName, null, "AdvancedProfile");
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Exception HttpGet AdvancedProfile", ex);
            }

            return(RedirectToAction("Index", "Home"));
        }
コード例 #8
0
        /// <summary>
        /// Gets attribute of a user by its key.
        /// </summary>
        public static string GetAttribute(this PhiUser user, string key)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            var userAttribute = user.UserAttributes
                                .FirstOrDefault(ca => ca.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase));

            if (userAttribute == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(userAttribute.Value))
            {
                return(null);
            }

            return(userAttribute.Value);
        }
コード例 #9
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new PhiUser()
                {
                    UserName = model.Email, Email = model.Email, DateCreated = DateTime.UtcNow
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id,
                                                     GlobalResources.ConfirmYourAccount,
                                                     String.Format(GlobalResources.ConfirmYourAccountContent, callbackUrl, "*****@*****.**"),
                                                     String.Format(GlobalResources.ConfirmYourAccountContentPlainText, callbackUrl, "*****@*****.**"));

                    await UserManager.SendEmailAsync(null, "Новый пользователь", "Новый пользователь пришёл! Ура! User: "******"Index", "Home");
                    ViewBag.Link = callbackUrl;
                    return(View("DisplayEmail"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #10
0
 /// <summary>
 /// Gets a value indicating whether user is registered
 /// </summary>
 /// <param name="user">PhiUser</param>
 /// <returns>Result</returns>
 public static bool IsRegistered(this PhiUser user)
 {
     return(IsInUserRole(user, SystemUserRoleNames.Registered));
 }
コード例 #11
0
        public new ActionResult Profile(ProfileViewModel model)
        {
            try
            {
                PhiUser currentUser = _userStore.FindByNameAsync(User.Identity.GetUserName()).Result;

                if (ModelState.IsValid)
                {
                    UserProfile profile = _userProfileStore.GetUserProfileById(User.Identity.GetUserId());

                    if (currentUser != null)
                    {
                        currentUser.FirstName = model.FirstName;
                        currentUser.LastName  = model.LastName;
                        currentUser.UserName  = model.UserName;
                    }

                    this._userStore.UpdateAsync(currentUser);

                    if (profile != null)
                    {
                        profile.Gender = profile == null ? null : model.Gender;

                        // Save location.
                        if (model.IsCheckedLocation)
                        {
                            var locationParts = model.Location.Split(',');

                            if (locationParts != null && locationParts.Length >= 2)
                            {
                                var location = DataHelper.TryToGetLocation(null, locationParts[0].Trim(), locationParts[1].Trim(),
                                                                           (locationParts.Length >= 2 && locationParts[2] != null) ? locationParts[2].Trim() : null, _dataStore);
                                if (location != null)
                                {
                                    profile.LocationId = location.Id;
                                }
                            }
                        }
                    }

                    this._userProfileStore.Update(profile);

                    return(RedirectToAction("AdvancedProfile"));
                }

                if (currentUser != null)
                {
                    model.Url = "";

                    // This data cannot come from POST because we use non-editing controls for it.
                    model.Email       = currentUser.Email;
                    model.DateCreated = currentUser.DateCreated;

                    if (currentUser.UserProfile != null)
                    {
                        model.AvatarPictureUrl = currentUser.UserProfile.AvatarPictureUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Exception HttpPost Profile", ex);
            }

            return(View(model));
        }