Inheritance: UserInfo, ISiteUser
コード例 #1
0
ファイル: InitialData.cs プロジェクト: joeaudette/cloudscribe
        public static SiteUser BuildInitialAdmin()
        {
            var adminUser = new SiteUser();
            adminUser.Email = "*****@*****.**";
            adminUser.NormalizedEmail = adminUser.Email.ToUpperInvariant();
            adminUser.DisplayName = "Admin";
            adminUser.UserName = "******";

            adminUser.EmailConfirmed = true;
            adminUser.AccountApproved = true;

            // clear text password will be hashed upon login
            // this format allows migrating from mojoportal
            adminUser.PasswordHash = "admin||0"; //pwd/salt/format 

            return adminUser;
        }
コード例 #2
0
        public async Task<ISiteUser> FetchByLoginName(int siteId, string userName, bool allowEmailFallback)
        {
            using (DbDataReader reader = await dbSiteUser.GetSingleUserByLoginName(siteId, userName, allowEmailFallback))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    return user;

                }
            }

            return null;
        }
コード例 #3
0
        public async Task<ISiteUser> FetchByConfirmationGuid(int siteId, Guid confirmGuid)
        {  
            using (DbDataReader reader = await dbSiteUser.GetUserByRegistrationGuid(siteId, confirmGuid))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    if (user.SiteId == siteId) { return user; }

                }
            }

            return null;
        }
コード例 #4
0
        public async Task<IList<ISiteUser>> GetUsersForClaim(
            int siteId,
            string claimType, 
            string claimValue)
        {
            IList<ISiteUser> users = new List<ISiteUser>();

            using (DbDataReader reader = await dbUserClaims.GetUsersByClaim(siteId, claimType, claimValue))
            {
                while (reader.Read())
                {
                    SiteUser user = new SiteUser();
                    user.LoadFromReader(reader);
                    users.Add(user);

                }

            }

            return users;
        }
コード例 #5
0
        public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            log.LogDebug("ExternalLoginConfirmation called with returnurl " + returnUrl);

            //if (signInManager.IsSignedIn(User))
            //{
            //    return RedirectToAction("Index", "Manage");
            //}

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await signInManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }

                var userName = model.Email.Replace("@", string.Empty).Replace(".", string.Empty);
                var userNameAvailable = await userManager.LoginIsAvailable(Guid.Empty, userName);
                if (!userNameAvailable)
                {
                    userName = model.Email;
                }

                var user = new SiteUser {
                    SiteId = Site.Id,
                    UserName = userName,
                    Email = model.Email,
                    AccountApproved = Site.RequireApprovalBeforeLogin ? false : true
                };
                var result = await userManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    log.LogDebug("ExternalLoginConfirmation user created ");

                    await ipAddressTracker.TackUserIpAddress(Site.Id, user.Id);

                    result = await userManager.AddLoginAsync(user, info);
                    if (result.Succeeded)
                    {
                        log.LogDebug("ExternalLoginConfirmation AddLoginAsync succeeded ");

                        
                        if (Site.RequireConfirmedEmail) // require email confirmation
                        {
                            var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                            var callbackUrl = Url.Action(new UrlActionContext
                            {
                                Action = "ConfirmEmail",
                                Controller = "Account",
                                Values = new { userId = user.Id.ToString(), code = code },
                                Protocol = HttpContext.Request.Scheme
                            });

                            emailSender.SendAccountConfirmationEmailAsync(
                                Site,
                                model.Email,
                                sr["Confirm your account"],
                                callbackUrl).Forget();

                            // this is needed to clear the external cookie - wasn't needed in rc2
                            await signInManager.SignOutAsync();

                            if (this.SessionIsAvailable())
                            {
                                this.AlertSuccess(sr["Please check your email inbox, we just sent you a link that you need to click to confirm your account"], true);

                                return Redirect("/");
                            }
                            else
                            {
                                return RedirectToAction("EmailConfirmationRequired", new { userId = user.Id, didSend = true });
                            }
                        }
                        else
                        {
                            if (Site.RequireApprovalBeforeLogin)
                            {
                                emailSender.AccountPendingApprovalAdminNotification(Site, user).Forget();

                                // this is needed to clear the external cookie - wasn't needed in rc2
                                await signInManager.SignOutAsync();

                                return RedirectToAction("PendingApproval", new { userId = user.Id, didSend = true });
                            }
                            else
                            {
                                await signInManager.SignInAsync(user, isPersistent: false);

                                if (!string.IsNullOrEmpty(returnUrl))
                                {
                                    return LocalRedirect(returnUrl);
                                }

                                return this.RedirectToSiteRoot(Site);
                            }
                        }

                        
                    }
                    else
                    {
                        log.LogDebug("ExternalLoginConfirmation AddLoginAsync failed ");
                    }
                }
                else
                {
                    log.LogDebug("ExternalLoginConfirmation failed to user created ");
                }

                AddErrors(result);
            }
            else
            {
                log.LogDebug("ExternalLoginConfirmation called with ModelStateInvalid ");
                model.RegistrationPreamble = Site.RegistrationPreamble;
                model.RegistrationAgreement = Site.RegistrationAgreement;
                model.AgreementRequired = Site.RegistrationAgreement.Length > 0;
            }

            ViewData["ReturnUrl"] = returnUrl;
            return View(model);
        }
コード例 #6
0
        public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            log.LogInformation("ExternalLoginConfirmation called with returnurl " + returnUrl);

            if (User.IsSignedIn())
            {
                return RedirectToAction("Index", "Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await signInManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new SiteUser {
                    SiteGuid = Site.SiteGuid,
                    SiteId = Site.SiteId,
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await userManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    log.LogInformation("ExternalLoginConfirmation user created ");

                    result = await userManager.AddLoginAsync(user, info);
                    if (result.Succeeded)
                    {
                        log.LogInformation("ExternalLoginConfirmation AddLoginAsync succeeded ");
                        await signInManager.SignInAsync(user, isPersistent: false);
                        return this.RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        log.LogInformation("ExternalLoginConfirmation AddLoginAsync failed ");
                    }
                }
                else
                {
                    log.LogInformation("ExternalLoginConfirmation failed to user created ");
                }

                AddErrors(result);
            }
            else
            {
                log.LogInformation("ExternalLoginConfirmation called with ModelStateInvalid ");
            }

            ViewData["ReturnUrl"] = returnUrl;
            return View(model);
        }
コード例 #7
0
        public async Task<IActionResult> UserEdit(EditUserViewModel model)
        {
            ISiteSettings selectedSite;
            // only server admin site can edit other sites settings
            if ((model.SiteGuid != siteManager.CurrentSite.SiteGuid) && (model.SiteGuid != Guid.Empty) && (siteManager.CurrentSite.IsServerAdminSite))
            {
                selectedSite = await siteManager.Fetch(model.SiteGuid);
            }
            else
            {
                selectedSite = siteManager.CurrentSite;
            }

            ViewData["Title"] = "New User";

            if (ModelState.IsValid)
            {
                if (model.UserId > -1)
                {
                    //editing an existing user
                    ISiteUser user = await UserManager.Fetch(selectedSite.SiteId, model.UserId);
                    if (user != null)
                    {
                        user.Email = model.Email;
                        user.FirstName = model.FirstName;
                        user.LastName = model.LastName;
                        user.UserName = model.LoginName;
                        user.DisplayName = model.DisplayName;
                        if (model.DateOfBirth.HasValue)
                        {
                            user.DateOfBirth = model.DateOfBirth.Value;
                        }
                        else
                        {
                            user.DateOfBirth = DateTime.MinValue;
                        }

                        bool result = await UserManager.Save(user);
                        if (result)
                        {
                            this.AlertSuccess(string.Format("user account for <b>{0}</b> was successfully updated.",
                            user.DisplayName), true);
                        }


                        return RedirectToAction("Index", "UserAdmin");
                    }
                }
                else
                {
                    var user = new SiteUser
                    {
                        SiteId = selectedSite.SiteId,
                        SiteGuid = selectedSite.SiteGuid,
                        UserName = model.LoginName,
                        Email = model.Email,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        DisplayName = model.DisplayName
                    };

                    if (model.DateOfBirth.HasValue)
                    {
                        user.DateOfBirth = model.DateOfBirth.Value;
                    }

                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        this.AlertSuccess(string.Format("user account for <b>{0}</b> was successfully created.",
                            user.DisplayName), true);

                        return RedirectToAction("Index", "UserAdmin");
                    }
                    AddErrors(result);
                }


            }

            // If we got this far, something failed, redisplay form
            return View(model);

        }
コード例 #8
0
        public async Task<ISiteUser> Fetch(
            int siteId, 
            string email, 
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            using (DbDataReader reader = await dbSiteUser.GetSingleUser(
                siteId, 
                email,
                cancellationToken))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    return user;

                }
            }

            return null;
        }
コード例 #9
0
ファイル: UserRepository.cs プロジェクト: ludev/cloudscribe
        public async Task<ISiteUser> Fetch(int siteId, Guid userGuid, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();

            using (DbDataReader reader = dbSiteUser.GetSingleUser(userGuid))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    if (user.SiteId == siteId) { return user; }

                }
            }

            return null;
        }
コード例 #10
0
ファイル: InitialData.cs プロジェクト: ludev/cloudscribe
        private static async Task EnsureData(
            CoreDbContext db
            )
        {
            int rowsAffected = 0;


            int count = await db.Countries.CountAsync<GeoCountry>();
            if(count == 0)
            {
                foreach(GeoCountry c in cloudscribe.Core.Models.InitialData.BuildCountryList())
                {
                    db.Countries.Add(c);
                }

                rowsAffected = await db.SaveChangesAsync();
            }
            
            count = await db.States.CountAsync<GeoZone>();
            if (count == 0)
            {
                foreach (GeoZone c in cloudscribe.Core.Models.InitialData.BuildStateList())
                {
                    db.States.Add(c);
                }

                rowsAffected = await db.SaveChangesAsync();
            }

            

            count = await db.Languages.CountAsync<Language>();
            if (count == 0)
            {
                foreach (Language c in cloudscribe.Core.Models.InitialData.BuildLanguageList())
                {
                    db.Languages.Add(c);
                }

                rowsAffected = await db.SaveChangesAsync();
            }

            count = await db.Currencies.CountAsync<Currency>();
            if (count == 0)
            {
                foreach (Currency c in cloudscribe.Core.Models.InitialData.BuildCurrencyList())
                {
                    db.Currencies.Add(c);
                }

                rowsAffected = await db.SaveChangesAsync();
            }

                
            count = await db.Sites.CountAsync<SiteSettings>();
            if (count == 0)
            {
                // create first site
                SiteSettings newSite = new SiteSettings();
                newSite.SiteId = 0;
                newSite.SiteGuid = Guid.NewGuid();
                newSite.SiteName = "Sample Site";
                newSite.IsServerAdminSite = true;

                newSite.Layout = "Default_Layout.cshtml";

                newSite.AllowNewRegistration = true;
                newSite.AllowUserFullNameChange = false;
                newSite.AutoCreateLdapUserOnFirstLogin = true;
                newSite.ReallyDeleteUsers = true;
                newSite.LdapPort = 389;
                newSite.LdapRootDN = string.Empty;
                newSite.LdapServer = string.Empty;
                newSite.UseEmailForLogin = true;
                newSite.UseLdapAuth = false;
                newSite.UseSecureRegistration = false;
                newSite.UseSslOnAllPages = false;


                //0 = clear, 1= hashed, 2= encrypted
                //newSite.PasswordFormat = 1;

                newSite.RequiresQuestionAndAnswer = false;
                newSite.MaxInvalidPasswordAttempts = 10;
                newSite.PasswordAttemptWindowMinutes = 5;
                newSite.MinReqNonAlphaChars = 0;
                newSite.MinRequiredPasswordLength = 7;

                db.Sites.Add(newSite);
                
                rowsAffected = await db.SaveChangesAsync();
                   
            }

            // ensure roles
            count = await db.Roles.CountAsync<SiteRole>();
            if (count == 0)
            {
                SiteSettings site = await db.Sites.SingleOrDefaultAsync<SiteSettings>(
                    s => s.SiteId > 0 && s.IsServerAdminSite == true);

                if(site != null)
                {
                    SiteRole adminRole = new SiteRole();
                    adminRole.RoleId = 0;
                    adminRole.RoleGuid = Guid.NewGuid();
                    adminRole.RoleName = "Admins";
                    adminRole.DisplayName = "Administrators";
                    adminRole.SiteId = site.SiteId;
                    adminRole.SiteGuid = site.SiteGuid;
                    db.Roles.Add(adminRole);
                    //rowsAffected = await db.SaveChangesAsync();
                        
                    SiteRole roleAdminRole = new SiteRole();
                    roleAdminRole.RoleId = 0;
                    roleAdminRole.RoleGuid = Guid.NewGuid();
                    roleAdminRole.RoleName = "Role Admins";
                    roleAdminRole.DisplayName = "Role Administrators";
                    roleAdminRole.SiteId = site.SiteId;
                    roleAdminRole.SiteGuid = site.SiteGuid;
                    db.Roles.Add(roleAdminRole);
                    //rowsAffected = await db.SaveChangesAsync();
                    
                    SiteRole contentAdminRole = new SiteRole();
                    contentAdminRole.RoleId = 0;
                    contentAdminRole.RoleGuid = Guid.NewGuid();
                    contentAdminRole.RoleName = "Content Administrators";
                    contentAdminRole.DisplayName = "Content Administrators";
                    contentAdminRole.SiteId = site.SiteId;
                    contentAdminRole.SiteGuid = site.SiteGuid;
                    db.Roles.Add(contentAdminRole);

                    SiteRole authenticatedUserRole = new SiteRole();
                    authenticatedUserRole.RoleId = 0;
                    authenticatedUserRole.RoleGuid = Guid.NewGuid();
                    authenticatedUserRole.RoleName = "Authenticated Users";
                    authenticatedUserRole.DisplayName = "Authenticated Users";
                    authenticatedUserRole.SiteId = site.SiteId;
                    authenticatedUserRole.SiteGuid = site.SiteGuid;
                    db.Roles.Add(authenticatedUserRole);

                    
                    rowsAffected = await db.SaveChangesAsync();
                    
                   
                }

            }

            // ensure admin user
            count = await db.Users.CountAsync<SiteUser>();
            
            if (count == 0)
            {
                SiteSettings site = await db.Sites.SingleOrDefaultAsync<SiteSettings>(
                    s => s.SiteId > 0 && s.IsServerAdminSite == true);
                    
                if (site != null)
                {
                    SiteRole role
                        = await db.Roles.SingleOrDefaultAsync(
                            x => x.SiteId == site.SiteId && x.RoleName == "Admins");

                    if(role != null)
                    {
                        SiteUser adminUser = new SiteUser();
                        adminUser.SiteId = site.SiteId;
                        adminUser.SiteGuid = site.SiteGuid;
                        adminUser.Email = "*****@*****.**";
                        adminUser.LoweredEmail = adminUser.Email;
                        adminUser.DisplayName = "Admin";
                        adminUser.UserName = "******";
                        adminUser.UserId = 0;
                        adminUser.UserGuid = Guid.NewGuid();

                        adminUser.EmailConfirmed = true;
                        adminUser.AccountApproved = true;

                        // clear text password will be hashed upon login
                        // this format allows migrating from mojoportal
                        adminUser.PasswordHash = "admin||0"; //pwd/salt/format 

                        db.Users.Add(adminUser);
                        
                        rowsAffected = await db.SaveChangesAsync();
                        
                        if(rowsAffected > 0 && adminUser.UserId > -1)
                        {
                            UserRole ur = new UserRole();
                            ur.Id = 0;
                            ur.RoleGuid = role.RoleGuid;
                            ur.RoleId = role.RoleId;
                            ur.UserGuid = adminUser.UserGuid;
                            ur.UserId = adminUser.UserId;

                            db.UserRoles.Add(ur);
                            rowsAffected = await db.SaveChangesAsync();

                        }
                    }

                }

            }
            
        }
コード例 #11
0
ファイル: SiteManager.cs プロジェクト: okusnadi/cloudscribe
        public async Task<bool> CreateRequiredRolesAndAdminUser(
            SiteSettings site)
        {

            SiteRole adminRole = new SiteRole();
            adminRole.DisplayName = "Admins";
            //adminRole.DisplayName = "Administrators";
            adminRole.SiteId = site.SiteId;
            adminRole.SiteGuid = site.SiteGuid;
            bool result = await userRepo.SaveRole(adminRole);
            adminRole.DisplayName = "Administrators";
            result = await userRepo.SaveRole(adminRole);

            SiteRole roleAdminRole = new SiteRole();
            roleAdminRole.DisplayName = "Role Admins";
            roleAdminRole.SiteId = site.SiteId;
            roleAdminRole.SiteGuid = site.SiteGuid;
            result = await userRepo.SaveRole(roleAdminRole);

            roleAdminRole.DisplayName = "Role Administrators";
            result = await userRepo.SaveRole(roleAdminRole);

            SiteRole contentAdminRole = new SiteRole();
            contentAdminRole.DisplayName = "Content Administrators";
            contentAdminRole.SiteId = site.SiteId;
            contentAdminRole.SiteGuid = site.SiteGuid;
            result = await userRepo.SaveRole(contentAdminRole);

            SiteRole authenticatedUserRole = new SiteRole();
            authenticatedUserRole.DisplayName = "Authenticated Users";
            authenticatedUserRole.SiteId = site.SiteId;
            authenticatedUserRole.SiteGuid = site.SiteGuid;
            result = await userRepo.SaveRole(authenticatedUserRole);

            //SiteRole newsletterAdminRole = new SiteRole();
            //newsletterAdminRole.DisplayName = "Newsletter Administrators";
            //newsletterAdminRole.SiteId = site.SiteId;
            //newsletterAdminRole.SiteGuid = site.SiteGuid;
            //userRepository.SaveRole(newsletterAdminRole);

            // if using related sites mode there is a problem if we already have user [email protected]
            // and we create another one in the child site with the same email and login so we need to make it different
            // we could just skip creating this user since in related sites mode all users come from the first site
            // but then if the config were changed to not related sites mode there would be no admin user
            // so in related sites mode we create one only as a backup in case settings are changed later
            int countOfSites = await siteRepo.GetCount();
            string siteDifferentiator = string.Empty;
            if (
                (countOfSites >= 1)
                && (multiTenantOptions.UseRelatedSitesMode)
                )
            {
                if (site.SiteId > 1)
                {
                    siteDifferentiator = site.SiteId.ToInvariantString();
                }
            }

            //mojoMembershipProvider membership = Membership.Provider as mojoMembershipProvider;
            //bool overridRelatedSiteMode = true;
            SiteUser adminUser = new SiteUser();
            adminUser.SiteId = site.SiteId;
            adminUser.SiteGuid = site.SiteGuid;
            adminUser.Email = "admin" + siteDifferentiator + "@admin.com";
            adminUser.DisplayName = "Admin";
            adminUser.UserName = "******" + siteDifferentiator;

            adminUser.EmailConfirmed = true;
            adminUser.ApprovedForLogin = true;
            adminUser.Password = "******";
            adminUser.PasswordFormat = 0;

            //if (membership != null)
            //{
            //    adminUser.Password = membership.EncodePassword(site, adminUser, "admin");
            //}

            adminUser.PasswordQuestion = "What is your user name?";
            adminUser.PasswordAnswer = "admin";

            result = await userRepo.Save(adminUser);

            //siteUserManager.AddPassword(adminUser.UserGuid.ToString(), "admin");

            //siteUserManager.Create(adminUser, "admin");
            //var result = siteUserManager.CreateAsync(adminUser, "admin");
            //if (result.Succeeded)
            //{
            //}
            result = await userRepo.AddUserToRole(
                adminRole.RoleId,
                adminRole.RoleGuid,
                adminUser.UserId,
                adminUser.UserGuid);

            return result;

        }
コード例 #12
0
        public async Task<ISiteUser> FetchByConfirmationGuid(int siteId, Guid confirmGuid)
        {
            if (multiTenantOptions.UseRelatedSitesMode) { siteId = multiTenantOptions.RelatedSiteId; }

            using (DbDataReader reader = dbSiteUser.GetUserByRegistrationGuid(siteId, confirmGuid))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    if (user.SiteId == siteId) { return user; }

                }
            }

            return null;
        }
コード例 #13
0
        public async Task<ISiteUser> Fetch(int siteId, Guid userGuid)
        {
            if (multiTenantOptions.UseRelatedSitesMode) { siteId = multiTenantOptions.RelatedSiteId; }

            using (DbDataReader reader = dbSiteUser.GetSingleUser(userGuid))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    if (user.SiteId == siteId) { return user; }

                }
            }

            return null;
        }
コード例 #14
0
ファイル: SiteUser.cs プロジェクト: ludev/cloudscribe
        public static SiteUser FromISiteUser(ISiteUser user)
        {
            SiteUser u = new SiteUser();
            u.AccountApproved = user.AccountApproved;
            u.AuthorBio = user.AuthorBio;
            u.AvatarUrl = user.AvatarUrl;
            u.Comment = user.Comment;
            u.Country = user.Country;
            u.CreatedUtc = user.CreatedUtc;
            u.DateOfBirth = user.DateOfBirth;
            u.DisplayInMemberList = user.DisplayInMemberList;
            u.DisplayName = user.DisplayName;
            u.Email = user.Email;
            u.EmailChangeGuid = user.EmailChangeGuid;
            u.EmailConfirmed = user.EmailConfirmed;
            u.FailedPasswordAnswerAttemptCount = user.FailedPasswordAnswerAttemptCount;
            u.FailedPasswordAnswerAttemptWindowStart = user.FailedPasswordAnswerAttemptWindowStart;
            u.FailedPasswordAttemptCount = user.FailedPasswordAttemptCount;
            u.FailedPasswordAttemptWindowStart = user.FailedPasswordAttemptWindowStart;
            u.FirstName = user.FirstName;
            u.Gender = user.Gender;
            //u.Id = user.Id;
            u.IsDeleted = user.IsDeleted;
            u.IsLockedOut = user.IsLockedOut;
            u.LastActivityDate = user.LastActivityDate;
            u.LastLockoutDate = user.LastLockoutDate;
            u.LastLoginDate = user.LastLoginDate;
            u.LastName = user.LastName;
            u.LastPasswordChangedDate = user.LastPasswordChangedDate;
            u.LockoutEndDateUtc = user.LockoutEndDateUtc;
            u.LoweredEmail = user.LoweredEmail;
            u.MustChangePwd = user.MustChangePwd;
            u.NewEmail = user.NewEmail;
            u.PasswordHash = user.PasswordHash;
            u.PasswordResetGuid = user.PasswordResetGuid;
            u.PhoneNumber = user.PhoneNumber;
            u.PhoneNumberConfirmed = user.PhoneNumberConfirmed;
            u.RegisterConfirmGuid = user.RegisterConfirmGuid;
            u.RolesChanged = user.RolesChanged;
            u.SecurityStamp = user.SecurityStamp;
            u.Signature = user.Signature;
            u.SiteGuid = user.SiteGuid;
            u.SiteId = user.SiteId;
            u.State = user.State;
            u.TimeZoneId = user.TimeZoneId;
            u.Trusted = user.Trusted;
            u.TwoFactorEnabled = user.TwoFactorEnabled;
            u.UserGuid = user.UserGuid;
            u.UserId = user.UserId;
            u.UserName = user.UserName;
            u.WebSiteUrl = user.WebSiteUrl;
           

            return u;
        }
コード例 #15
0
ファイル: SiteUser.cs プロジェクト: ReinhardHsu/cloudscribe
        //public string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();

        public static SiteUser FromISiteUser(ISiteUser user)
        {
            SiteUser u = new SiteUser();
           // u.ConcurrencyStamp = user.ConcurrencyStamp;
            //Guid id = user.Id;
            if (user.Id != Guid.Empty) u.Id = user.Id;
            //SiteUser u = new SiteUser(id);
            
            u.AccessFailedCount = user.AccessFailedCount;
            u.AccountApproved = user.AccountApproved;
            u.AuthorBio = user.AuthorBio;
            u.AvatarUrl = user.AvatarUrl;
            u.CanAutoLockout = user.CanAutoLockout;
            u.Comment = user.Comment;
            //u.Country = user.Country;
            u.CreatedUtc = user.CreatedUtc;
            u.LastModifiedUtc = user.LastModifiedUtc;

            if (user.DateOfBirth.HasValue)
            {
                u.DateOfBirth = user.DateOfBirth.Value;
            }
            
            u.DisplayInMemberList = user.DisplayInMemberList;
            u.DisplayName = user.DisplayName;
            u.Email = user.Email;
            u.EmailConfirmed = user.EmailConfirmed;
            u.FirstName = user.FirstName;
            u.Gender = user.Gender;
            u.IsDeleted = user.IsDeleted;
            u.IsLockedOut = user.IsLockedOut;
            
            if(user.LastLoginUtc.HasValue)
            {
                u.LastLoginUtc = user.LastLoginUtc.Value;
            }
            
            u.LastName = user.LastName;
            if(user.LastPasswordChangeUtc.HasValue)
            {
                u.LastPasswordChangeUtc = user.LastPasswordChangeUtc.Value;
            }
            
            u.LockoutEndDateUtc = user.LockoutEndDateUtc;
            u.MustChangePwd = user.MustChangePwd;
            u.NormalizedEmail = user.NormalizedEmail;
            u.NormalizedUserName = user.NormalizedUserName;
            u.NewEmail = user.NewEmail;
            u.NewEmailApproved = user.NewEmailApproved;
            
            u.PasswordHash = user.PasswordHash;
            u.PhoneNumber = user.PhoneNumber;
            u.PhoneNumberConfirmed = user.PhoneNumberConfirmed;
            
            u.RolesChanged = user.RolesChanged;
            u.SecurityStamp = user.SecurityStamp;
            u.Signature = user.Signature;
            u.SiteId = user.SiteId;
            
            //u.State = user.State;
            u.TimeZoneId = user.TimeZoneId;
            u.Trusted = user.Trusted;
            u.TwoFactorEnabled = user.TwoFactorEnabled;
            
            u.UserName = user.UserName;
            u.WebSiteUrl = user.WebSiteUrl;
           

            return u;
        }
コード例 #16
0
        public async Task<ISiteUser> FetchByConfirmationGuid(
            int siteId, 
            Guid confirmGuid, 
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            using (DbDataReader reader = await dbSiteUser.GetUserByRegistrationGuid(
                siteId, 
                confirmGuid,
                cancellationToken))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    if (user.SiteId == siteId) { return user; }

                }
            }

            return null;
        }
コード例 #17
0
        public async Task<IList<ISiteUser>> GetUsersForClaim(
            int siteId,
            string claimType,
            string claimValue)
        {
            IList<ISiteUser> users = new List<ISiteUser>();

            if (multiTenantOptions.UseRelatedSitesMode) { siteId = multiTenantOptions.RelatedSiteId; }

            using (DbDataReader reader = await dbUserClaims.GetUsersByClaim(siteId, claimType, claimValue))
            {
                while (reader.Read())
                {
                    SiteUser user = new SiteUser();
                    user.LoadFromReader(reader);
                    users.Add(user);

                }

            }

            return users;
        }
コード例 #18
0
        public async Task<ISiteUser> FetchByLoginName(
            int siteId, 
            string userName, 
            bool allowEmailFallback, 
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            using (DbDataReader reader = await dbSiteUser.GetSingleUserByLoginName(
                siteId, 
                userName, 
                allowEmailFallback,
                cancellationToken))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    return user;

                }
            }

            return null;
        }
コード例 #19
0
        public async Task<ISiteUser> Fetch(int siteId, string email)
        {
            if (multiTenantOptions.UseRelatedSitesMode) { siteId = multiTenantOptions.RelatedSiteId; }

            using (DbDataReader reader = await dbSiteUser.GetSingleUser(siteId, email))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    return user;

                }
            }

            return null;
        }
コード例 #20
0
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            ViewData["Title"] = "Register";

            if ((Site.CaptchaOnRegistration)&& (Site.RecaptchaPublicKey.Length > 0))
            {
                model.RecaptchaSiteKey = Site.RecaptchaPublicKey;     
            }

            model.RegistrationPreamble = Site.RegistrationPreamble;
            model.RegistrationAgreement = Site.RegistrationAgreement;

            bool isValid = ModelState.IsValid;
            if (isValid)
            {
                if ((Site.CaptchaOnRegistration)&& (Site.RecaptchaPublicKey.Length > 0))
                {
                    string recpatchaSecretKey = Site.RecaptchaPrivateKey;
                    
                    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

                    if (!captchaResponse.Success)
                    {
                        //if (captchaResponse.ErrorCodes.Count <= 0)
                        //{
                        //    return View(model);
                        //}

                        ////TODO: log these errors rather than show them in the ui
                        //var error = captchaResponse.ErrorCodes[0].ToLower();
                        //switch (error)
                        //{
                        //    case ("missing-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is missing.");     
                        //        break;
                        //    case ("invalid-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is invalid or malformed.");
                        //        break;
                        //    case ("missing-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is missing.");
                        //        break;
                        //    case ("invalid-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is invalid or malformed.");
                        //        break;
                        //    default:
                        //        ModelState.AddModelError("recaptchaerror", "Error occured. Please try again");
                        //        break;
                        //}

                        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
                        isValid = false;
                        
                    }

                }

                //if (Site.RegistrationAgreement.Length > 0)
                //{
                //    if (!model.AgreeToTerms)
                //    {
                //        ModelState.AddModelError("agreementerror", "You must agree to the terms");
                //        isValid = false;
                //    }
                //}

                if (!isValid)
                {
                    return View(model);
                }

                var user = new SiteUser
                {
                    UserName = model.LoginName.Length > 0? model.LoginName : model.Email.Replace("@",string.Empty).Replace(".",string.Empty),
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    DisplayName = model.DisplayName
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }


                var result = await userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    
                    if(Site.UseSecureRegistration) // require email confirmation
                    {
                        var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
                        var callbackUrl = Url.Action("ConfirmEmail", "Account", 
                            new { userId = user.Id, code = code }, 
                            protocol: HttpContext.Request.Scheme);

                        await emailSender.SendAccountConfirmationEmailAsync(
                            Site,
                            model.Email, 
                            "Confirm your account",
                            callbackUrl);

                        if (this.SessionIsAvailable())
                        {
                            this.AlertSuccess("Please check your email inbox, we just sent you a link that you need to click to confirm your account", true);
                            
                            return Redirect("/");
                        }
                        else
                        {
                            return RedirectToAction("EmailConfirmationRequired", new { userGuid = user.Id, didSend = true });
                        }

                    }
                    else
                    {
                        if(Site.RequireApprovalBeforeLogin)
                        {
                            //TODO: send notification to admins about request for approval

                        }
                        else
                        {
                            await signInManager.SignInAsync(user, isPersistent: false);
                            return Redirect("/");
                        }
                    }

                   
                    
                }
                AddErrors(result);
            }
            //else
            //{
            //    this.AlertDanger("model was invalid", true);
            //}

            // If we got this far, something failed, redisplay form
            return View(model);
        }
コード例 #21
0
        public async Task<ISiteUser> FetchByLoginName(int siteId, string userName, bool allowEmailFallback)
        {
            if (multiTenantOptions.UseRelatedSitesMode) { siteId = multiTenantOptions.RelatedSiteId; }

            using (DbDataReader reader = await dbSiteUser.GetSingleUserByLoginName(siteId, userName, allowEmailFallback))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    return user;

                }
            }

            return null;
        }
コード例 #22
0
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            ViewData["Title"] = sr["Register"];
            if ((Site.CaptchaOnRegistration)&& (Site.RecaptchaPublicKey.Length > 0))
            {
                model.RecaptchaSiteKey = Site.RecaptchaPublicKey;     
            }
            model.UseEmailForLogin = Site.UseEmailForLogin;
            model.RegistrationPreamble = Site.RegistrationPreamble;
            model.RegistrationAgreement = Site.RegistrationAgreement;
            model.AgreementRequired = Site.RegistrationAgreement.Length > 0;
            model.ExternalAuthenticationList = signInManager.GetExternalAuthenticationSchemes();

            bool isValid = ModelState.IsValid;
            if (isValid)
            {
                if ((Site.CaptchaOnRegistration)&& (Site.RecaptchaPublicKey.Length > 0))
                {
                    string recpatchaSecretKey = Site.RecaptchaPrivateKey;
                    
                    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

                    if (!captchaResponse.Success)
                    {
                        //if (captchaResponse.ErrorCodes.Count <= 0)
                        //{
                        //    return View(model);
                        //}

                        ////TODO: log these errors rather than show them in the ui
                        //var error = captchaResponse.ErrorCodes[0].ToLower();
                        //switch (error)
                        //{
                        //    case ("missing-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is missing.");     
                        //        break;
                        //    case ("invalid-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is invalid or malformed.");
                        //        break;
                        //    case ("missing-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is missing.");
                        //        break;
                        //    case ("invalid-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is invalid or malformed.");
                        //        break;
                        //    default:
                        //        ModelState.AddModelError("recaptchaerror", "Error occured. Please try again");
                        //        break;
                        //}

                        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
                        isValid = false;
                        
                    }

                }

                if (Site.RegistrationAgreement.Length > 0)
                {
                    if (!model.AgreeToTerms)
                    {
                        ModelState.AddModelError("agreementerror", sr["You must agree to the terms"]);
                        isValid = false;
                    }
                }

                var userName = model.Username.Length > 0 ? model.Username : model.Email.Replace("@", string.Empty).Replace(".", string.Empty);
                var userNameAvailable = await userManager.LoginIsAvailable(Guid.Empty, userName);
                if(!userNameAvailable)
                {
                    ModelState.AddModelError("usernameerror", sr["Username not accepted please try a different value"]);
                    isValid = false;
                }

                if (!isValid)
                {
                    return View(model);
                }

                var user = new SiteUser
                {
                    UserName = userName,
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    DisplayName = model.DisplayName,
                    AccountApproved = Site.RequireApprovalBeforeLogin ? false : true
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }
                
                var result = await userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await ipAddressTracker.TackUserIpAddress(Site.Id, user.Id);

                    if (Site.RequireConfirmedEmail) // require email confirmation
                    {
                        var code = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action(new UrlActionContext {
                            Action ="ConfirmEmail",
                            Controller = "Account",
                            Values = new { userId = user.Id.ToString(), code = code },
                            Protocol= HttpContext.Request.Scheme
                            });

                        emailSender.SendAccountConfirmationEmailAsync(
                            Site,
                            model.Email, 
                            sr["Confirm your account"],
                            callbackUrl).Forget();

                        if (this.SessionIsAvailable())
                        {
                            this.AlertSuccess(sr["Please check your email inbox, we just sent you a link that you need to click to confirm your account"], true);
                            
                            return Redirect("/");
                        }
                        else
                        {
                            return RedirectToAction("EmailConfirmationRequired", new { userId = user.Id, didSend = true });
                        }
                    }
                    else
                    {
                        if(Site.RequireApprovalBeforeLogin)
                        {
                            emailSender.AccountPendingApprovalAdminNotification(Site, user).Forget();      
                            return RedirectToAction("PendingApproval", new { userId = user.Id, didSend = true });
                        }
                        else
                        {
                            await signInManager.SignInAsync(user, isPersistent: false);
                            return this.RedirectToSiteRoot(Site);
                        }
                    }
                }
                AddErrors(result);
            }
            
            // If we got this far, something failed, redisplay form
            return View(model);
        }
コード例 #23
0
        public async Task<IActionResult> Register(EditUserViewModel model)
        {
            ViewData["Title"] = "Register";

            if ((Site.RequireCaptchaOnRegistration)&& (Site.RecaptchaPublicKey.Length > 0))
            {
                model.RecaptchaSiteKey = Site.RecaptchaPublicKey;     
            }

            model.RegistrationPreamble = Site.RegistrationPreamble;
            model.RegistrationAgreement = Site.RegistrationAgreement;

            bool isValid = ModelState.IsValid;
            if (isValid)
            {
                if ((Site.RequireCaptchaOnRegistration)&& (Site.RecaptchaPublicKey.Length > 0))
                {
                    string recpatchaSecretKey = Site.RecaptchaPrivateKey;
                    
                    var captchaResponse = await this.ValidateRecaptcha(Request, recpatchaSecretKey);

                    if (!captchaResponse.Success)
                    {
                        //if (captchaResponse.ErrorCodes.Count <= 0)
                        //{
                        //    return View(model);
                        //}

                        ////TODO: log these errors rather than show them in the ui
                        //var error = captchaResponse.ErrorCodes[0].ToLower();
                        //switch (error)
                        //{
                        //    case ("missing-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is missing.");     
                        //        break;
                        //    case ("invalid-input-secret"):
                        //        ModelState.AddModelError("recaptchaerror", "The secret parameter is invalid or malformed.");
                        //        break;
                        //    case ("missing-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is missing.");
                        //        break;
                        //    case ("invalid-input-response"):
                        //        ModelState.AddModelError("recaptchaerror", "The response parameter is invalid or malformed.");
                        //        break;
                        //    default:
                        //        ModelState.AddModelError("recaptchaerror", "Error occured. Please try again");
                        //        break;
                        //}

                        ModelState.AddModelError("recaptchaerror", "reCAPTCHA Error occured. Please try again");
                        isValid = false;
                        
                    }

                }

                //if (Site.RegistrationAgreement.Length > 0)
                //{
                //    if (!model.AgreeToTerms)
                //    {
                //        ModelState.AddModelError("agreementerror", "You must agree to the terms");
                //        isValid = false;
                //    }
                //}

                if (!isValid)
                {
                    return View(model);
                }

                var user = new SiteUser
                {
                    UserName = model.LoginName.Length > 0? model.LoginName : model.Email.Replace("@",string.Empty).Replace(".",string.Empty),
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    DisplayName = model.DisplayName
                };

                if (model.DateOfBirth.HasValue)
                {
                    user.DateOfBirth = model.DateOfBirth.Value;
                }


                var result = await userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme);
                    //await MessageServices.SendEmailAsync(model.Email, "Confirm your account",
                    //    "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                    await signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                    
                }
                AddErrors(result);
            }
            //else
            //{
            //    this.AlertDanger("model was invalid", true);
            //}

            // If we got this far, something failed, redisplay form
            return View(model);
        }
コード例 #24
0
ファイル: SiteManager.cs プロジェクト: freemsly/cloudscribe
        public async Task<bool> CreateAdminUser(ISiteSettings site)
        {

            ISiteRole adminRole = await userRepo.FetchRole(site.SiteId, "Admins");

            if(adminRole == null)
            {
                throw new InvalidOperationException("Admins role could nto be found so cannot create admin user");
            }
            

            // if using related sites mode there is a problem if we already have user [email protected]
            // and we create another one in the child site with the same email and login so we need to make it different
            // we could just skip creating this user since in related sites mode all users come from the first site
            // but then if the config were changed to not related sites mode there would be no admin user
            // so in related sites mode we create one only as a backup in case settings are changed later
            int countOfSites = await siteRepo.GetCount();
            string siteDifferentiator = string.Empty;
            if (
                (countOfSites >= 1)
                && (multiTenantOptions.UseRelatedSitesMode)
                )
            {
                if (site.SiteId > 1)
                {
                    siteDifferentiator = site.SiteId.ToInvariantString();
                }
            }


            SiteUser adminUser = new SiteUser();
            adminUser.SiteId = site.SiteId;
            adminUser.SiteGuid = site.SiteGuid;
            adminUser.Email = "admin" + siteDifferentiator + "@admin.com";
            adminUser.DisplayName = "Admin";
            adminUser.UserName = "******" + siteDifferentiator;

            adminUser.EmailConfirmed = true;
            adminUser.AccountApproved = true;

            // clear text password will be hashed upon login
            // this format allows migrating from mojoportal
            adminUser.PasswordHash = "admin||0"; //pwd/salt/format 


            bool result = await userRepo.Save(adminUser);
            
            result = await userRepo.AddUserToRole(
                adminRole.RoleId,
                adminRole.RoleGuid,
                adminUser.UserId,
                adminUser.UserGuid);

            return result;

        }
コード例 #25
0
 public Task AddClaims(SiteUser user, ClaimsIdentity identity)
 {
     // do nothing
     return Task.FromResult(0);
 }
コード例 #26
0
        public async Task<ISiteUser> Fetch(int siteId, Guid userGuid)
        { 
            using (DbDataReader reader = await dbSiteUser.GetSingleUser(userGuid))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    if (user.SiteId == siteId) { return user; }

                }
            }

            return null;
        }
コード例 #27
0
        public async Task<IList<ISiteUser>> GetUsersInRole(
            int siteId,
            string roleName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            IList<ISiteUser> users = new List<ISiteUser>();

            ISiteRole role = await FetchRole(siteId, roleName);
            int roleId = -3;
            if (role != null)
            {
                roleId = role.RoleId;
            }

            using (DbDataReader reader = await dbRoles.GetUsersInRole(
                siteId, 
                roleId, 
                string.Empty, 
                1, 
                100000,
                cancellationToken))
            {
                while (reader.Read())
                {
                    SiteUser user = new SiteUser();
                    user.LoadFromReader(reader);
                    users.Add(user);

                }

            }

            return users;
        }
コード例 #28
0
        public async Task<ISiteUser> Fetch(int siteId, string email)
        { 
            using (DbDataReader reader = await dbSiteUser.GetSingleUser(siteId, email))
            {
                if (reader.Read())
                {
                    SiteUser user = new SiteUser();

                    user.LoadFromReader(reader);

                    return user;

                }
            }

            return null;
        }
コード例 #29
0
        public async Task<IList<ISiteUser>> GetUsersForClaim(
            int siteId,
            string claimType,
            string claimValue,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            IList<ISiteUser> users = new List<ISiteUser>();

            using (DbDataReader reader = await dbUserClaims.GetUsersByClaim(
                siteId, 
                claimType, 
                claimValue,
                cancellationToken))
            {
                while (reader.Read())
                {
                    SiteUser user = new SiteUser();
                    user.LoadFromReader(reader);
                    users.Add(user);

                }

            }

            return users;
        }
コード例 #30
0
        public async Task<IList<ISiteUser>> GetUsersInRole(
            int siteId,
            string roleName)
        {
            IList<ISiteUser> users = new List<ISiteUser>();

            ISiteRole role = await FetchRole(siteId, roleName);
            int roleId = -3;
            if(role != null)
            {
                roleId = role.RoleId;
            }

            using (DbDataReader reader = await dbRoles.GetUsersInRole(siteId, roleId, string.Empty, 1, 100000))
            {
                while (reader.Read())
                {
                    SiteUser user = new SiteUser();
                    user.LoadFromReader(reader);
                    users.Add(user);

                }

            }

            return users;
        }
コード例 #31
0
        public static SiteUser FromISiteUser(ISiteUser user)
        {
            SiteUser u = new SiteUser();

            if (user.Id != Guid.Empty)
            {
                u.Id = user.Id;
            }

            u.AccessFailedCount = user.AccessFailedCount;
            u.AccountApproved   = user.AccountApproved;
            u.AuthorBio         = user.AuthorBio;
            u.AvatarUrl         = user.AvatarUrl;
            u.CanAutoLockout    = user.CanAutoLockout;
            u.Comment           = user.Comment;

            u.CreatedUtc      = user.CreatedUtc;
            u.LastModifiedUtc = user.LastModifiedUtc;

            if (user.DateOfBirth.HasValue)
            {
                u.DateOfBirth = user.DateOfBirth.Value;
            }

            u.DisplayInMemberList = user.DisplayInMemberList;
            u.DisplayName         = user.DisplayName;
            u.Email          = user.Email;
            u.EmailConfirmed = user.EmailConfirmed;
            u.FirstName      = user.FirstName;
            u.Gender         = user.Gender;
            u.IsDeleted      = user.IsDeleted;
            u.IsLockedOut    = user.IsLockedOut;

            if (user.LastLoginUtc.HasValue)
            {
                u.LastLoginUtc = user.LastLoginUtc.Value;
            }

            u.LastName = user.LastName;
            if (user.LastPasswordChangeUtc.HasValue)
            {
                u.LastPasswordChangeUtc = user.LastPasswordChangeUtc.Value;
            }

            u.LockoutEndDateUtc  = user.LockoutEndDateUtc;
            u.MustChangePwd      = user.MustChangePwd;
            u.NormalizedEmail    = user.NormalizedEmail;
            u.NormalizedUserName = user.NormalizedUserName;
            u.NewEmail           = user.NewEmail;
            u.NewEmailApproved   = user.NewEmailApproved;

            u.PasswordHash         = user.PasswordHash;
            u.PhoneNumber          = user.PhoneNumber;
            u.PhoneNumberConfirmed = user.PhoneNumberConfirmed;

            u.RolesChanged  = user.RolesChanged;
            u.SecurityStamp = user.SecurityStamp;
            u.Signature     = user.Signature;
            u.SiteId        = user.SiteId;

            //u.State = user.State;
            u.TimeZoneId       = user.TimeZoneId;
            u.Trusted          = user.Trusted;
            u.TwoFactorEnabled = user.TwoFactorEnabled;

            u.UserName             = user.UserName;
            u.WebSiteUrl           = user.WebSiteUrl;
            u.EmailConfirmSentUtc  = user.EmailConfirmSentUtc;
            u.AgreementAcceptedUtc = user.AgreementAcceptedUtc;


            return(u);
        }