public String Activate(int id, string value, int? rowId,
               int? columnPosition, int? columnId, string columnName)
        {
            using (var db = new UsersContext())
            {

                var account = db.UserProfiles.FirstOrDefault(a => a.UserId == id);
                if (account == null)
                {
                    return "ID 为 " + id + " 的账号不存在";
                }
                switch (columnPosition)
                {
                    case 3:
                        bool activated = (int.Parse(value) == 1);
                        if (!activated)
                            return value;
                       try
                        {
                            var confirmationToken = db.Database.SqlQuery<string>("select ConfirmationToken from webpages_Membership where UserId={0}", new Object[] { id }).Single();
                            if (!WebSecurity.ConfirmAccount(account.UserName, confirmationToken))
                                throw new Exception("账号确认令牌无效");
                        }
                        catch (Exception e)
                        {
                            return "批准账号失败:" + e.Message;
                        }
                        break;
                    default:
                        break;
                }
                return value;
            }
        }
 public static void Initialize()
 {
     if (!WebSecurityInitializer.isInitialized)
     {
         lock (WebSecurityInitializer.isInitializedSyncObject)
         {
             if (!WebSecurityInitializer.isInitialized)
             {
                 WebSecurityInitializer.isInitialized = true;
                 Database.SetInitializer<UsersContext>(null);
                 try
                 {
                     using (UsersContext context = new UsersContext())
                     {
                         if (!context.Database.Exists())
                         {
                             ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                         }
                     }
                     bool autoCreateTables = true;
                     WebSecurity.InitializeDatabaseConnection("db", "guestservice_UserProfile", "userId", "userName", autoCreateTables);
                 }
                 catch (System.Exception ex)
                 {
                     throw new System.InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                 }
             }
         }
     }
 }
        public override System.Configuration.SettingsPropertyValueCollection GetPropertyValues(System.Configuration.SettingsContext context, System.Configuration.SettingsPropertyCollection collection)
        {
            using (UsersContext db = new UsersContext())
            {
                SettingsPropertyValueCollection settings = new SettingsPropertyValueCollection();

                string userName = context["UserName"].ToString();
                UserProfile userProfile = db.UsersProfiles.Find(userName);

                if (userProfile == null)
                {
                    foreach (SettingsProperty profileProperty in collection)
                    {
                        SettingsPropertyValue value = new SettingsPropertyValue(collection[profileProperty.Name]);
                        value.PropertyValue = null;
                        settings.Add(value);
                    }
                }

                else

                {

                    foreach (SettingsProperty profileProperty in collection)
                    {
                        SettingsPropertyValue value = new SettingsPropertyValue(collection[profileProperty.Name]);
                        value.PropertyValue = userProfile.GetType().GetProperty(profileProperty.Name).GetValue(userProfile, null);
                        settings.Add(value);
                    }
                }

                return settings;
            }
        }
示例#4
0
 public override string[] GetAllRoles()
 {
     using (var usersContext = new UsersContext())
     {
         return usersContext.Roles.Select(r => r.short_Title).ToArray();
     }
 }
示例#5
0
        static void Main()
        {
            UsersContext context = new UsersContext();
            context.Database.Initialize(true);
                               
            #region //11.	Get Users by Email Provider
            //Console.WriteLine("Please enter email provider: ");
            //string emailProvider = Console.ReadLine();
            //GetUsersByEmailProvider(context, emailProvider);
            #endregion

            #region // 12.	Count Users with Bigger Pictures
            // Console.WriteLine("Please enter number of pixels: ");
            // int numberOfPixels = int.Parse(Console.ReadLine());
            // int countOfBigPictures = GetCountOfBiggerPictures(context, numberOfPixels);
            // Console.WriteLine($"{countOfBigPictures} users have profile pictures wider than {numberOfPixels} pixels");
            #endregion

            #region // 13.	Remove Inactive Users                
            //Console.WriteLine("Please enter a date: ");
            //string enteredDateString = Console.ReadLine();
            //DateTime enteredDate = DateTime.Parse(enteredDateString); 
            //RemoveInactiveUsers(context, enteredDate);
            #endregion
        }
			public SimpleMembershipInitializer()
			{
				Database.SetInitializer<UsersContext>(null);

				try
				{
					using (var context = new UsersContext())
					{
						if (!context.Database.Exists())
						{
							// Create the SimpleMembership database without Entity Framework migration schema
							((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
						}
					}

					WebSecurity.InitializeDatabaseConnection(
						"DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
				}
				catch (Exception ex)
				{
					throw new InvalidOperationException(
						"The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", 
						ex);
				}
			}
 public override string[] GetRolesForUser(string username)
 {
     using (UsersContext db = new UsersContext())
     {
         User user = db.Users.Find(username);
         return user.UserInRoles.Select(x => x.Role).Select(y => y.Name).ToArray();
     }
 }
示例#8
0
 private static void GetUsersByEmailProvider(UsersContext context, string emailProvider)
 {
     IEnumerable<User> wantedUsers = context.Users.Where(user => user.Email.EndsWith(emailProvider));
     foreach (User wantedUser in wantedUsers)
     {
         Console.WriteLine($"{wantedUser.Username} {wantedUser.Password} - {wantedUser.Age}");
     }
 }   
示例#9
0
 public NewMessageViewModel()
 {
     _usersContext = ContextFactory.GetUserContext();
     _messageContext = ContextFactory.GetMessageContext();
     _saveMessageCommand = new RelayCommand(OnSaveMessage);
     UpdateForUsersRole();
     LoadData();
 }
 public override bool IsUserInRole(string username, string roleName)
 {
     var usersContext = new UsersContext();
     var user = usersContext.Users.SingleOrDefault(u => u.UserName == username);
     if (user == null)
         return false;
     return user.UserRoles != null && user.UserRoles.Select(
          u => u.Role).Any(r => r.RoleName == roleName);
 }
示例#11
0
 public MessagesViewModel()
 {
     _context = ContextFactory.GetMessageContext();
     _usersContext = ContextFactory.GetUserContext();
     AppMessages.MailDeletedMessage.Register(this, OnMessageDeleted);
     AppMessages.MailSentMessage.Register(this, OnMessageSent);
     IsLoggedIn = true;
     //Load all messages for current user sorted
     LoadData();
 }
示例#12
0
 public override string[] GetRolesForUser(string username)
 {
     using (var usersContext = new UsersContext())
     {
         var user = usersContext.Users.SingleOrDefault(u => u.LASTNAME == username);
         if (user == null)
             return new string[]{};
         return user.UserRoles == null ? new string[] { } : user.UserRoles.Select(u => u.Role).Select(u => u.short_Title).ToArray();
     }
 }
 public bool VerifySession(string ipAddress, string sessionId)
 {
     using (var ctx = new UsersContext())
     {
         DateTime timeout = DateTime.UtcNow.AddSeconds(-TimeoutSeconds);
         return ctx.UserSessions.Any(s => s.SqrlId == sessionId &&
                                          s.AuthenticatedDatetime == null &&
                                          s.CreatedDatetime >= timeout);
     }
 }
        public SaveResult SaveChanges(JObject saveBundle)
        {
            var context = new UsersContext();
            var username = User.Identity.Name;
            var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);

            TheLogger.Write(string.Format("User {0} saved changes.", username), TraceEventType.Information);

            return _repository.SaveChanges(saveBundle);
        }
        public ActionResult Users()
        {
            IEnumerable<UserProfile> users;
            using (UsersContext db = new UsersContext())
            {
                users = db.UserProfiles.ToList();
            }

            ViewBag.Roles = System.Web.Security.Roles.GetAllRoles();

            return View(users);
        }
 public override string[] GetRolesForUser(string username)
 {
     var usersContext = new UsersContext();
     //var user = usersContext.Users.SingleOrDefault(u => u.UserName == username);
     var user = usersContext.GetUser(username);
     if (user == null)
         return new string[] { };
     return user.UserRoles == null
         ? new string[] { }
         : GetUserRoles(user.UserId).Select(u => u.Role).Select(u => u.RoleName).ToArray();
     //user.UserRoles.Select(u => u.Role).Select(u => u.RoleName).ToArray();
 }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);
                bool isInitDb = Boolean.Parse(ConfigurationManager.AppSettings["initdb"].ToString());
                if (!isInitDb)
                {
                    try
                    {
                        using (var context = new UsersContext())
                        {
                            if (!context.Database.Exists())
                            {
                                // Create the SimpleMembership database without Entity Framework migration schema
                                ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                            }
                        }

                        //WebSecurity.InitializeDatabaseConnection("DuozhiduocaiConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                        //var roles = (SimpleRoleProvider)Roles.Provider;

                        if (!Roles.RoleExists("Admin"))
                            Roles.CreateRole("Admin");
                        if (!Roles.RoleExists("Member"))
                            Roles.CreateRole("Member");
                        if (!WebSecurity.UserExists("administrator"))
                        {
                            WebSecurity.CreateUserAndAccount(
                            "administrator",
                            "yangaiche@huodong");
                        }
                        if (!WebSecurity.UserExists("yangaiche"))
                        {
                            WebSecurity.CreateUserAndAccount("yangaiche", "yangaiche@wechat");
                        }
                        //var roles = Roles.GetRolesForUser("admin");
                        if (!Roles.GetRolesForUser("administrator").Contains("Admin"))
                        {
                            Roles.AddUsersToRoles(new[] { "administrator" }, new[] { "Admin" });
                        }
                        if (!Roles.GetRolesForUser("yangaiche").Contains("Admin"))
                        {
                            Roles.AddUsersToRoles(new[] { "yangaiche" }, new[] { "Admin" });
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                    }
                }
            }
示例#18
0
        private static int GetCountOfBiggerPictures(UsersContext context, int numberOfPixels)
        {
            IEnumerable<User> userWithPictures = context.Users.Where(user => user.ProfilePicture != null);
            int count = 0;

            foreach (User userWithPicture in userWithPictures)
            {
                if (userWithPicture.ProfileImage.Width > numberOfPixels)
                {
                    count++;
                }
            }

            return count;
        }
 public override int DeleteProfiles(string[] usernames)
 {
     using (UsersContext db = new UsersContext())
     {
         List<UserProfile> profiles = new List<UserProfile>();
         int i;
         for (i = 0; i < usernames.Count(); i++)
         {
             string userName=usernames[i];
             profiles.Add(db.UsersProfiles.Find(userName));
         }
         db.UsersProfiles.RemoveRange(profiles);
         db.SaveChanges();
         return i;
     }
 }
示例#20
0
 public bool AddUser(RegisterExternalLoginModel model)
 {
     using (var db = new UsersContext())
     {
         var user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
         // Check if user already exists
         if (user == null)
         {
             // Insert name into the profile table
             db.UserProfiles.Add(new UserProfile {UserName = model.UserName});
             db.SaveChanges();
             return true;
         }
         return false;
     }
 }
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            using (UsersContext db = new UsersContext())
            {
                foreach (string username in usernames)
                {
                    foreach (string rolename in roleNames)
                    {
                        UserInRole userInRole = new UserInRole();
                        userInRole.UserName = (string) Membership.GetUser(username).ProviderUserKey;
                        userInRole.RoleId = db.Roles.FirstOrDefault(x => x.Name == rolename).Id;
                        db.UsersInRoles.Add(userInRole);
                        db.SaveChanges();
                    }

                }
            }
        }
示例#22
0
        private static void RemoveInactiveUsers(UsersContext context, DateTime logDate)
        {
            List<User> users = context.Users.Where(user => user.LastTimeLoggedIn < logDate && !user.IsDeleted).ToList();
            foreach (User user in users)
            {
                user.IsDeleted = true;
            }
            if (users.Count == 0)
            {
                Console.WriteLine("No users have been deleted");
            }
            else
            {
                Console.WriteLine($"{users.Count} user has been deleted");
            }

            context.SaveChanges();
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("MusicStoreEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                    var roleProvider = (SimpleRoleProvider)Roles.Provider;
                    if (!roleProvider.RoleExists("Administrator"))
                    {
                        roleProvider.CreateRole(("Administrator"));
                    }
                    var membershipProvider = (SimpleMembershipProvider)Membership.Provider;
                    if (membershipProvider.GetUser("StoreAdmin", false) == null)
                    {
                        membershipProvider.CreateUserAndAccount("StoreAdmin", "Pass@word1");
                    }
                    var userRoles = roleProvider.GetRolesForUser("StoreAdmin").ToList();
                    if (!userRoles.Contains("Administrator"))
                    {
                        roleProvider.AddUsersToRoles(new[] { "StoreAdmin" }, new[] { "Administrator" });
                    }

                }
                catch (InvalidOperationException ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
                catch (ArgumentNullException ex)
                {
                    throw new ArgumentNullException("The ASP.NET Simple Membership database could not identify an Administrator. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                  using (var context = new UsersContext())
                  {
                if (!context.Database.Exists())
                {
                  // Create the SimpleMembership database without Entity Framework migration schema
                  ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                }
                  }

                  WebSecurity.InitializeDatabaseConnection("SecurityDb", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                  throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }

                using (var context = new LiteDispatchDbContext(new ModelCreator()))
                {
                  if (context.Database.Exists()) return;
                  context.Database.CreateIfNotExists();
                  using (var transManager = Container.GlobalContext.TransFactory.CreateManager())
                  {
                transManager.ExecuteCommand(locator =>
                  {
                var haulier = locator.FindAll<Haulier>().SingleOrDefault(h => h.Name == "BlueWhale");
                if (haulier != null)
                {
                  return Mapper.Map<Haulier, HaulierModel>(haulier);
                }
                haulier = Haulier.Create(locator, new HaulierModel { Name = "BlueWhale" });
                return Mapper.Map<Haulier, HaulierModel>(haulier);
                  });
                  }
                }
            }
        public ActionResult Upload(UserDetailsModel IG)
        {
            if (!Request.IsAuthenticated)
            {
                return(RedirectToAction("Login", "Account"));
            }
            // Apply Validation Here
            //Set the other profile pictures as inactive

            //Save the profile image
            if (IG.File.ContentLength > (2 * 1024 * 1024))
            {
                ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                return(RedirectToAction("Profile"));
            }

            /* if (!(IG.File.ContentType == "image/jpeg" || IG.File.ContentType == "image/gif"))
             * {
             *   ModelState.AddModelError("CustomError", "File type allowed : jpeg and gif");
             *   return RedirectToAction("Profile");
             * }*/
            Helpers.UpdateProfilePicStatus(System.Web.HttpContext.Current.User.Identity.Name);
            byte[] data = new byte[IG.File.ContentLength];
            IG.File.InputStream.Read(data, 0, IG.File.ContentLength);
            ProfilePics details = new ProfilePics();
            int         id      = Helpers.FetchUserId(System.Web.HttpContext.Current.User.Identity.Name);

            details.userid       = id;
            details.pic          = data;
            details.datecreated  = DateTime.Now;
            details.datemodified = DateTime.Now;
            details.status       = 1;//Status 1 means the profile picture is the active 1.
            using (UsersContext dc = new UsersContext())
            {
                dc.ProfilePics.Add(details);
                dc.SaveChanges();
            }
            return(RedirectToAction("Profile"));
        }
示例#26
0
 public UserService(
     IOptions <UsersSettings> options,
     IEmailService emailService,
     UsersContext context,
     IDistributedCache cache,
     IMapper mapper,
     ILogger <UserService> logger
     )
 {
     this._options = options ??
                     throw new ArgumentNullException(nameof(options));
     this._emailService = emailService ??
                          throw new ArgumentNullException(nameof(emailService));
     this._context = context ??
                     throw new ArgumentNullException(nameof(context));
     this._cache = cache ??
                   throw new ArgumentNullException(nameof(cache));
     this._mapper = mapper ??
                    throw new ArgumentNullException(nameof(mapper));
     this._logger = logger ??
                    throw new ArgumentNullException(nameof(logger));
 }
示例#27
0
        public ActionResult AddData()
        {
            UsersContext    db       = new UsersContext();
            string          a        = WebSecurity.CurrentUserName;
            UserData        model    = new UserData();
            List <UserData> TempList = new List <UserData>();

            TempList = db.UsersData.ToList();
            for (int i = 0; i < TempList.Count; i++)
            {
                if (TempList[i].UserProfile.UserId == WebSecurity.CurrentUserId)
                {
                    model = TempList[i];
                    ViewBag.currentUser = TempList[i];
                    break;
                }
            }
            db.Dispose();
            ViewBag.NotRead = HomeController.GetNotReadMessagesCount();

            return(View("AddData", model));
        }
示例#28
0
        public ActionResult RecoverPasswordPage(LocalPasswordModel model)

        {
            if (model.NewPassword == null || model.ConfirmPassword == null)
            {
                ModelState.AddModelError("NewPassword", "Ошибка! Заполните все поля");
                return(View(model));
            }
            if (model.NewPassword != model.ConfirmPassword)
            {
                ModelState.AddModelError("NewPassword", "Ошибка! Пароли должны совпадать");
                return(View(model));
            }
            int    s        = WebSecurity.GetUserIdFromPasswordResetToken(model.OldPassword);
            string FindUser = "";

            WebSecurity.ResetPassword(model.OldPassword, model.NewPassword);
            UsersContext       db = new UsersContext();
            List <UserProfile> _userProfileList = db.UserProfiles.ToList();

            for (int i = 0; i < _userProfileList.Count; i++)
            {
                if (_userProfileList[i].UserId == s)
                {
                    FindUser = _userProfileList[i].UserName;
                    break;
                }
            }
            bool logget = WebSecurity.Login(FindUser, model.NewPassword);

            if (logget)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View());
            }
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
示例#30
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Создание базы данных SimpleMembership без схемы миграции Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Не удалось инициализировать базу данных ASP.NET Simple Membership. Чтобы получить дополнительные сведения, перейдите по адресу: http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // 创建不包含 Entity Framework 迁移架构的 SimpleMembership 数据库
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("无法初始化 ASP.NET Simple Membership 数据库。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Создание базы данных SimpleMembership без схемы миграции Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Не удалось инициализировать базу данных ASP.NET Simple Membership. Чтобы получить дополнительные сведения, перейдите по адресу: http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public ActionResult SendMessage(SendMessageModel model, string username)
        {
            if (username == User.Identity.Name || !ModelState.IsValid)
            {
                return(View(model));
            }
            using (UsersContext db = new UsersContext())
            {
                List <string> temp = (from UserProfile in db.UserProfiles where UserProfile.UserName == username select UserProfile.UserName).ToList();
                if (!temp.Any())
                {
                    ModelState.AddModelError("", "Error, user does not exist");
                    return(View(model));
                }

                db.Messages.Add(new SN.Models.Messages {
                    From = WebSecurity.GetUserId(User.Identity.Name), Date = DateTime.Now, IsRead = false, Text = model.Text, To = WebSecurity.GetUserId(username)
                });
                db.SaveChanges();
            }
            return(RedirectToAction("Messages", "Messages"));
        }
示例#35
0
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Crear la base de datos SimpleMembership sin el esquema de migración de Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("No se pudo inicializar la base de datos de ASP.NET Simple Membership. Para obtener más información, consulte http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public void AuthenticateSession(string userId, string ipAddress, string sessionId)
        {
            using (var ctx = new UsersContext())
            {
                DateTime timeout = DateTime.UtcNow.AddSeconds(-TimeoutSeconds);
                var usrSession = ctx.UserSessions.FirstOrDefault(s => s.SqrlId == sessionId &&
                                                                      s.AuthenticatedDatetime == null &&
                                                                      s.CreatedDatetime >= timeout);
                 if (usrSession == null)
                 {
                     return;
                 }

                usrSession.AuthenticatedDatetime = DateTime.UtcNow;
                usrSession.UserId = userId;

                ctx.SaveChanges();
            }

            var hubContext = GlobalHost.ConnectionManager.GetHubContext<LoginHub>();
            hubContext.Clients.Group(sessionId).login();
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Créer la base de données SimpleMembership sans schéma de migration Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Impossible d'initialiser la base de données ASP.NET Simple Membership. Pour plus d'informations, consultez la page http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
示例#38
0
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Créer la base de données SimpleMembership sans schéma de migration Entity Framework
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Impossible d'initialiser la base de données ASP.NET Simple Membership. Pour plus d'informations, consultez la page http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
示例#39
0
        private User SetupFormsAuthTicket(string userName, bool persistanceFlag)
        {
            User user;

            using (var usersContext = new UsersContext())
            {
                user = usersContext.Users.First(x => x.UserName == userName);
            }
            var userId     = user.UserId;
            var userData   = userId.ToString(CultureInfo.InvariantCulture);
            var authTicket = new FormsAuthenticationTicket(1,                           //version
                                                           userName,                    // user name
                                                           DateTime.Now,                //creation
                                                           DateTime.Now.AddMinutes(30), //Expiration
                                                           persistanceFlag,             //Persistent
                                                           userData);

            var encTicket = FormsAuthentication.Encrypt(authTicket);

            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
            return(user);
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // 创建不包含 Entity Framework 迁移架构的 SimpleMembership 数据库
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("无法初始化 ASP.NET Simple Membership 数据库。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public ActionResult Create(ApplyProject applyproject, HttpPostedFileBase AttachFile = null)
        {
            String FileUrl;

            if (ModelState.IsValid)
            {
                if (AttachFile != null)
                {
                    AttachFile = Request.Files["AttachFile"];
                    if (AttachFile.ContentLength > 0)
                    {
                        FileUrl = "upload/";
                        String Path = Server.MapPath("~/") + FileUrl;
                        String FileName = DateTime.UtcNow.ToString("yyyy" + "MM" + "dd" + "HH" + "mm" + "ss" + "ffffff");
                        FileUrl = FileUrl + FileName;
                        if (!Directory.Exists(Path))
                            Directory.CreateDirectory(Path);
                        String extstr = System.IO.Path.GetExtension(AttachFile.FileName);
                        AttachFile.SaveAs(Path + FileName + extstr);
                        applyproject.ProjectAttach = FileUrl + extstr;
                    }
                }
                else
                {
                    applyproject.ProjectAttach = "";
                }
                applyproject.ApplyPeopleDepartment = "实验中心";
                applyproject.ApplyPeopleName = "王凯斯";
                UsersContext xx = new UsersContext();
                db.ApplyProjectSet.Add(applyproject);
                db.SaveChanges();
                string phyPath = HttpContext.Request.MapPath("/");
                OfficeController oc = new OfficeController();
                oc.BuildWord(applyproject, phyPath);
                return RedirectToAction("Index");
            }

            return View(applyproject);
        }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            var args = new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return(null);
            }

            var user = GetUser(username, true);

            if (user == null)
            {
                var userObj = new User {
                    UserName = username, Password = GetMd5Hash(password), UserEmailAddress = email
                };

                using (var usersContext = new UsersContext())
                {
                    usersContext.AddUser(userObj);
                }

                status = MembershipCreateStatus.Success;

                return(GetUser(username, true));
            }
            status = MembershipCreateStatus.DuplicateUserName;

            return(null);
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Entity Framework 마이그레이션 스키마 없이 SimpleMembership 데이터베이스 생성
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("ASP.NET Simple Membership 데이터베이스를 초기화할 수 없습니다. 자세한 내용은 http://go.microsoft.com/fwlink/?LinkId=256588을 참조하십시오.", ex);
                }
            }
示例#44
0
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("UsersConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                    SimpleRoleProvider       roles      = (SimpleRoleProvider)Roles.Provider;
                    SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;

                    if (!roles.RoleExists("Admin"))
                    {
                        roles.CreateRole("Admin");
                    }
                    if (!roles.RoleExists("User"))
                    {
                        roles.CreateRole("User");
                    }
                    if (membership.GetUser("Admin", false) == null)
                    {
                        membership.CreateUserAndAccount("Admin", "Admin");
                        roles.AddUsersToRoles(new[] { "Admin" }, new[] { "Admin" });
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
示例#45
0
        public ActionResult ForgotPassword(string UserName)
        {
            //check user existance
            var user = Membership.GetUser(UserName);

            if (user == null)
            {
                TempData["Message"] = "User Not exist.";
            }
            else
            {
                //generate password token
                var token = WebSecurity.GeneratePasswordResetToken(UserName);
                //create url with above token
                var resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { un = UserName, rt = token }, "http") + "'>Reset Password</a>";
                //get user emailid
                UsersContext db      = new UsersContext();
                var          emailid = (from i in db.UserProfiles
                                        where i.UserName == UserName
                                        select i.EmailId).FirstOrDefault();
                //send mail
                string subject = "Password Reset Token";
                string body    = "<b>Please find the Password Reset Token</b><br/>" + resetLink; //edit it
                try
                {
                    SendEMail(emailid, subject, body);
                    TempData["Message"] = "Mail Sent.";
                }
                catch (Exception ex)
                {
                    TempData["Message"] = "Error occured while sending email." + ex.Message;
                }
                //only for testing
                TempData["Message"] = resetLink;
            }

            return(View());
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("MusicStoreEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                    var roleProvider = (SimpleRoleProvider)Roles.Provider;
                    if (!roleProvider.RoleExists("Administrator"))
                    {
                        roleProvider.CreateRole(("Administrator"));
                    }
                    var membershipProvider = (SimpleMembershipProvider)Membership.Provider;
                    if (membershipProvider.GetUser("StoreAdmin", false) == null)
                    {
                        membershipProvider.CreateUserAndAccount("StoreAdmin", "Pass@word1");
                    }
                    var userRoles = roleProvider.GetRolesForUser("StoreAdmin").ToList();
                    if (!userRoles.Contains("Administrator"))
                    {
                        roleProvider.AddUsersToRoles(new[] { "StoreAdmin" }, new[] { "Administrator" });
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public void AuthenticateSession(string userId, string ipAddress, string sessionId)
        {
            using (var ctx = new UsersContext())
            {
                DateTime timeout    = DateTime.UtcNow.AddSeconds(-TimeoutSeconds);
                var      usrSession = ctx.UserSessions.FirstOrDefault(s => s.SqrlId == sessionId &&
                                                                      s.AuthenticatedDatetime == null &&
                                                                      s.CreatedDatetime >= timeout);
                if (usrSession == null)
                {
                    return;
                }

                usrSession.AuthenticatedDatetime = DateTime.UtcNow;
                usrSession.UserId = userId;

                ctx.SaveChanges();
            }

            var hubContext = GlobalHost.ConnectionManager.GetHubContext <LoginHub>();

            hubContext.Clients.Group(sessionId).login();
        }
示例#48
0
 private void tbLogin_TextChanged(object sender, EventArgs e)
 {
     if (!loginRegex.IsMatch(MetaBackEnd.getCorrectLogin(tbLogin.Text)))
     {
         errorSign.SetError(tbLogin, "Login должен состоять из 6 to 50 letters of 'А-Яа-я0-9A-Za-z' and space");
         isLoginValid = false;
         return;
     }
     using (var ctx = new UsersContext())
     {
         var user = ctx.awp_users.SingleOrDefault(us => us.login_.ToLower() == tbLogin.Text.ToLower());
         if (user != default)
         {
             errorSign.SetError(tbLogin, "Login is already used");
             isLoginValid = false;
         }
         else
         {
             errorSign.SetError(tbLogin, "");
             isLoginValid = true;
         }
     }
 }
        public ActionResult Login(string returnUrl)
        {
            LoginModel model      = new LoginModel();
            HttpCookie authCookie = new HttpCookie("authCookie", "cookieValue")
            {
                Expires = DateTime.Now.AddMinutes(2)
            };

            ViewBag.ReturnUrl = returnUrl;
            // for admin registration
            UsersContext db    = new UsersContext();
            int          count = db.UserProfiles.Count();

            if (count == 0)
            {
                ViewBag.Register = true;
            }
            else
            {
                ViewBag.Register = false;
            }
            return(View());
        }
示例#50
0
        public ActionResult DisconnectMicrosoft()
        {
            if (this.MSAccountStatus != Controllers.MSAccountStatus.NotConnected)
            {
                // Remove the account association
                using (UsersContext db = new UsersContext())
                {
                    MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
                    if (msAccount != null)
                    {
                        db.MSAccounts.Remove(msAccount);
                        db.SaveChanges();
                    }
                }

                this.msAccountStatus = MSAccountStatus.NotConnected;
            }

            this.MSAuthClient.ClearSession(this.HttpContext);

            this.Response.Redirect(this.SiteRootPath + "account/connectmicrosoft");
            return(null);
        }
        public ActionResult ListEvents(DateTime startDate, DateTime endDate)
        {
            UserProfile userProfile = null;

            using (var context = new UsersContext())
            {
                userProfile = context.UserProfiles.FirstOrDefault(c => c.UserName == User.Identity.Name);
            }

            if (userProfile == null)
            {
                return(RedirectToAction("Register", "Account"));
            }

            var authenticator = GetAuthenticator();

            var service = new GoogleCalendarServiceProxy(authenticator);
            var model   = service.GetEvents(userProfile.Email, startDate, endDate);

            ViewBag.StartDate = startDate.ToShortDateString();
            ViewBag.EndDate   = endDate.ToShortDateString();
            return(View("Index", model));
        }
示例#52
0
        public static string GetFirst()
        {
            var builder = new ConfigurationBuilder();

            // установка пути к текущему каталогу
            builder.SetBasePath(Directory.GetCurrentDirectory());
            // получаем конфигурацию из файла appsettings.json
            builder.AddJsonFile("appsettings.json");
            // создаем конфигурацию
            var config = builder.Build();
            // получаем строку подключения
            string connectionString = config.GetConnectionString("DefaultConnection");

            var optionsBuilder = new DbContextOptionsBuilder <UsersContext>();
            var options        = optionsBuilder.UseSqlServer(connectionString).Options;


            using (UsersContext db = new UsersContext(options))
            {
                var users = db.Users.ToList();
                return(users[0].Name);
            }
        }
        public UsersContextTest()
        {
            _dateTime     = new DateTime(3001, 1, 1);
            _dateTimeMock = new Mock <IDateTime>();
            _dateTimeMock.Setup(m => m.Now).Returns(_dateTime);

            var options = new DbContextOptionsBuilder <UsersContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            _userContext = new UsersContext(options, _dateTimeMock.Object);

            _userContext.Users.Add(new Domain.Entities.User
            {
                Id           = 1,
                FirstName    = "John",
                LastName     = "Brown",
                Email        = "*****@*****.**",
                UserName     = "******",
                PasswordHash = "12345"
            });
            _userContext.SaveChanges();
        }
示例#54
0
        // АКТИВАЦИЯ АККАУНТА ЕСЛИ ПОЛЬЗОВАТЕЛЬ ПЕРЕШЕЛ ПО ССЫЛКЕ
        public ActionResult ActivationAccount(string ActivatonCode)
        {
            UsersContext      db        = new UsersContext();
            EmailModel        userEmail = new EmailModel();
            List <EmailModel> TempList  = new List <EmailModel>();

            TempList = db.EmailModels.ToList();
            for (int i = 0; i < TempList.Count; i++)
            {
                if (ActivatonCode == TempList[i].Key && WebSecurity.CurrentUserId == TempList[i].UserProfile.UserId)
                {
                    userEmail = TempList[i];
                    var EditUser = db.EmailModels
                                   .Where(c => c.Id == userEmail.Id)
                                   .FirstOrDefault();
                    EditUser.IsConfirm = true;
                    db.SaveChanges();
                    break;
                }
            }
            ViewBag.EmailError = null;
            return(RedirectToAction("Index", "Home"));
        }
示例#55
0
        public List <OutgoingIterationModel> GetPersons([FromBody] IncomingIterationRequest request)
        {
            var result = new List <OutgoingIterationModel>();

            using (var context = new UsersContext(Context, Configuration))
            {
                var dataResult = new List <UserAccounts>();

                var userRights = AutherizationManager.ValidateUserRights(request.ProjectId, UserId, context);
                if (userRights != null)
                {
                    result.Add(new OutgoingIterationModel
                    {
                        Text    = "All",
                        IconCss = "e-ddb-icons e-settings",
                        Url     = $"/Boards/Sprints?projectId={request.ProjectId}&&workItemType=7&&iteration={request.Iteration}&&person=0"
                    });
                    result.Add(new OutgoingIterationModel
                    {
                        Text    = "@Mine",
                        IconCss = "e-ddb-icons e-settings",
                        Url     = $"/Boards/Sprints?projectId={request.ProjectId}&&workItemType=7&&iteration={request.Iteration}&&person={userRights.Id}"
                    });
                    dataResult = context.GetProjectPersons(request.ProjectId);
                }
                dataResult.ForEach(x =>
                {
                    result.Add(new OutgoingIterationModel
                    {
                        Text    = x.GitUsername,
                        IconCss = "e-ddb-icons e-settings",
                        Url     = $"/Boards/Sprints?projectId={request.ProjectId}&&workItemType=7&&iteration={request.Iteration}&&person={x.Id}"
                    });
                });
            }
            return(result);
        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var userId = WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);

                    // save email
                    using (var ctxt = new UsersContext())
                    {
                        var profile = (from p in ctxt.UserProfiles
                                       where p.UserName == model.UserName
                                       select p)
                                      .SingleOrDefault();

                        profile.Email            = model.Email;
                        profile.HasEmailReminder = model.HasEmailReminder;
                        profile.DisplayName      = model.DisplayName;

                        ctxt.SaveChanges();

                        log.InfoFormat("Registered: User={0}, Pwd={1}, Email={2}", model.UserName, model.Password, model.Email);
                    }
                    return(RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#57
0
        public ActionResult Settings(LocalPasswordModel model)
        {
            ViewBag.NotRead = HomeController.GetNotReadMessagesCount();
            UsersContext    db           = new UsersContext();
            List <UserData> TempUserList = new List <UserData>();

            TempUserList = db.UsersData.ToList();
            for (int i = 0; i < TempUserList.Count; i++)
            {
                if (TempUserList[i].UserProfile.UserId == WebSecurity.CurrentUserId)
                {
                    ViewBag.currentUser = TempUserList[i];
                    break;
                }
            }
            if (String.IsNullOrEmpty(model.ConfirmPassword) || String.IsNullOrEmpty(model.OldPassword) ||
                String.IsNullOrEmpty(model.NewPassword))
            {
                ModelState.AddModelError("PasswordMessage", "Ошибка! Заполните все поля!");
                return(View(model));
            }
            if (model.ConfirmPassword != model.NewPassword)
            {
                ModelState.AddModelError("PasswordMessage", "Ошибка! Пароли не совпадают");
                return(View(model));
            }
            bool changePasswordSucceeded;

            changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
            if (!changePasswordSucceeded)
            {
                ModelState.AddModelError("PasswordMessage", "Ошибка! Данные введены не корректно");
                return(View(model));
            }
            ModelState.AddModelError("PasswordMessage", "Пароль успешно изменен!");
            return(View());
        }
示例#58
0
 public HomeController(
     IOptions <AppSettingsModel> appSettings,
     IOptionsSnapshot <DataSettingsModel> dataSettings,
     BlogContext db,
     UsersContext udb,
     AdminUtil adminUtil,
     BlogUtil blogUtil,
     CategoryUtil catUtil,
     ExpUtil expUtil,
     MessageUtil msgUtil,
     TagUtil tagUtil,
     UserManager <UserProfile> userManager,
     UploadUtil uploadUtil,
     RatingUtil ratingUtil,
     CacheService cacheService,
     IMemoryCache cache,
     IWebHostEnvironment env,
     ISearchProvider searchProvider)
 {
     _db             = db;
     _udb            = udb;
     _adminUtil      = adminUtil;
     _catUtil        = catUtil;
     _blogUtil       = blogUtil;
     _expUtil        = expUtil;
     _msgUtil        = msgUtil;
     _appSettings    = appSettings.Value;
     _dataSettings   = dataSettings.Value;
     _userManager    = userManager;
     _cache          = cache;
     _uploadUtil     = uploadUtil;
     _tagUtil        = tagUtil;
     _ratingUtil     = ratingUtil;
     _cacheService   = cacheService;
     _env            = env;
     _searchProvider = searchProvider;
 }
        public dynamic RequestAccess([FromBody] IncomingProjectAccount request)
        {
            dynamic cResult = new System.Dynamic.ExpandoObject();

            using (var context = new UsersContext(Context, Configuration))
            {
                var result = context.CheckProjectSignUpPolicy(request.ProjectId, string.Empty).Item1;
                if (result == true)
                {
                    var getUserAccountByEmail = context.GetUserAccountByName(request.email);
                    context.AssociatedProjectExistingMembers(new IncomingExistingProjectMembers {
                        ProjectId = request.ProjectId,
                        Accounts  = new List <OutgoingUserAccounts>
                        {
                            new OutgoingUserAccounts
                            {
                                AccountId          = getUserAccountByEmail.Id,
                                ChatChannels       = 1,
                                EditUserRights     = 0,
                                IterationOptions   = 0,
                                ScheduleManagement = 0,
                                ViewWorkItems      = 1,
                                WorkItemOption     = 1,
                                Documentation      = 0
                            }
                        }
                    });
                    cResult.Success = true;
                    return(cResult);
                }
                else
                {
                    cResult.Error = true;
                    return(cResult);
                }
            }
        }
 protected override void OnAuthorization(AuthorizationContext authContext)
 {
     if
     (
         !User.Identity.IsAuthenticated &&
         Request.LogonUserIdentity != null &&
         Request.LogonUserIdentity.IsAuthenticated
     )
     {
         var logonUserIdentity = Request.LogonUserIdentity.Name;
         if (!string.IsNullOrEmpty(logonUserIdentity))
         {
             if (logonUserIdentity.Contains("\\"))
             {
                 logonUserIdentity = logonUserIdentity.Substring(logonUserIdentity.IndexOf("\\") + 1);
             }
             var db        = new UsersContext();
             var loginUser =
                 db.UserProfiles.FirstOrDefault(x => x.UserName == logonUserIdentity);
             //Auto-Login Windows Identity
             if (loginUser == null)
             {
                 loginUser = CreateUser(db, logonUserIdentity);
             }
             if (loginUser != null)
             {
                 FormsAuthentication.SetAuthCookie(loginUser.UserName, true);
                 string returnUrl = Request.RawUrl;
                 if (!string.IsNullOrEmpty(returnUrl))
                 {
                     Response.Redirect(returnUrl);
                 }
                 Response.Redirect("~/");
             }
         }
     }
 }