public static AuthToken ValidateUser(string username, string password, bool requireActiveAccount)
        {
            DbContext context = DataController.CreateDbContext();

            User user = context.Users.FirstOrDefault(u => u.ID == username);

            if (user == null)
            {
                throw new AuthenticationException("Invalid login.");
            }

            if (DateTime.UtcNow - user.LastLoginDate < Settings.Default.MinTimeBetweenLoginAttempts)
            {
                throw new AuthenticationException(string.Format("Please wait at least {0} seconds between login attempts.", Settings.Default.MinTimeBetweenLoginAttempts.Seconds));
            }

            if (DateTime.UtcNow - user.LastLoginDate < Settings.Default.AccountLockDuration && user.LoginAttempts > Settings.Default.MaxLoginAttempts)
            {
                throw new AuthenticationException(string.Format("Your account has been locked for {0} minutes due to too many incorrect login attempts.", Settings.Default.AccountLockDuration.Minutes));
            }

            byte[] passwordHash = user.PasswordHash;

            byte[] computedHash = SaltAndHashPassword(password, user.PasswordSalt);

            bool isValid = Enumerable.SequenceEqual(computedHash, passwordHash);

            user.LastLoginDate = DateTime.UtcNow;

            AuthToken token = null;

            if (isValid)
            {
                DateTime expiresOn = DateTime.UtcNow + Settings.Default.SessionExpiryInterval;

                token = new AuthToken(username, GetCallerIPAddress(), expiresOn, user.IsAdmin,
                    Common.Helpers.RandomHelper.RandomLong());

                user.LoginAttempts = 0;
                context.SaveChanges();
            }
            else
            {
                user.LoginAttempts++;
                context.SaveChanges();

                if (user.LoginAttempts < Settings.Default.MaxLoginAttempts)
                {
                    throw new AuthenticationException("Invalid login.");
                }
                else
                {
                    throw new AuthenticationException(string.Format("Your account has been locked for {0} minutes due to too many incorrect login attempts.",
                        Settings.Default.AccountLockDuration.Minutes));
                }
            }

            return token;
        }
Exemple #2
0
 public static void Serialize(AuthToken token, Stream stream)
 {
     using (BinaryWriter writer = new BinaryWriter(stream))
     {
         writer.Write(token.Username);
         writer.Write(token.IPAddress);
         writer.Write(token.ExpiresOn.Ticks);
         writer.Write(token.IsAdmin);
         writer.Write(token.Random);
     }
 }
Exemple #3
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            HttpCookie authTokenCookie = Request.Cookies[Constants.AuthToken];

            AuthToken authToken;

            if (authTokenCookie != null && !string.IsNullOrEmpty(authTokenCookie.Value) &&
                UserController.ValidateSession(HttpUtility.UrlDecode(authTokenCookie.Value), out authToken))
            {
                AuthToken = authToken;
            }
        }
Exemple #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            base.OnInit(e);

            HttpCookie authTokenCookie = Request.Cookies[Constants.AuthToken];

            AuthToken authToken;

            if (authTokenCookie != null && !string.IsNullOrEmpty(authTokenCookie.Value) &&
                UserController.ValidateSession(HttpUtility.UrlDecode(authTokenCookie.Value), out authToken))
            {
                AuthToken = authToken;
            }
            else
            {
                Response.Redirect("~/Login");
                Response.Close();
            }
        }
        public static void UpdateUser(string username, string firstName, string lastName, string emailAddress, AuthToken token)
        {
            if (!token.IsAdmin)
            {
                throw new AuthenticationException("Admin must perform this action");
            }

            DbContext context = DataController.CreateDbContext();

            User user = context.Users.FirstOrDefault(u => u.ID == username);

            if (user == null)
            {
                throw new AuthenticationException("User does not exist!");
            }

            if (EmailAddressExists(emailAddress, username))
            {
                throw new AuthenticationException("Email address is already in use");
            }

            user.FirstName = firstName;
            user.LastName = lastName;
            user.EmailAddress = emailAddress;

            context.SaveChanges();
        }
        public static AuthToken KeepSessionAlive(AuthToken token)
        {
            DateTime expiresOn = DateTime.UtcNow + Settings.Default.SessionExpiryInterval;

            return new AuthToken(token.Username, GetCallerIPAddress(), expiresOn, token.IsAdmin, Common.Helpers.RandomHelper.RandomLong());
        }
        public static void ValidateAntiForgeryToken(string tokenString, AuthToken authToken)
        {
            AntiForgeryToken antiForgeryToken;

            if (!ValidateAntiForgeryToken(tokenString, out antiForgeryToken))
            {
                throw new AuthenticationException("Invalid token.");
            }

            if (!string.Equals(antiForgeryToken.Username, authToken.Username))
            {
                throw new AuthenticationException("Invalid token.");
            }
        }
        public static void CreateUser(string username, string password, string emailAddress, string firstName, string lastName, AuthToken token, bool isAdmin)
        {
            if (!token.IsAdmin)
            {
                throw new AuthenticationException("Admin must perform this action");
            }

            DbContext context = DataController.CreateDbContext();

            if (UserExists(username))
            {
                throw new AuthenticationException("Username is taken.");
            }

            if (EmailAddressExists(emailAddress))
            {
                throw new AuthenticationException("Email address is already in use.");
            }

            CreateUser(context, username, password, emailAddress, firstName, lastName, isAdmin);

            context.SaveChanges();

            EmailController.SendNewUserEmail(firstName, lastName, username, emailAddress);
        }
        public static bool ValidateSession(string token, out AuthToken authToken)
        {
            byte[] tokenBytes = EncryptionHelper.DecryptToken(Convert.FromBase64String(token));

            using (MemoryStream memoryStream = new MemoryStream(tokenBytes))
            {
                authToken = AuthToken.Deserialize(memoryStream);
            }

            return ValidateAuthToken(authToken, Settings.Default.SessionExpiryInterval);
        }
        public static string CreateSessionCookie(AuthToken token)
        {
            string encryptedToken = Convert.ToBase64String(EncryptionHelper.EncryptToken(token.AsBytes()));

            return HttpUtility.UrlEncode(encryptedToken);
        }
        public static void DeleteUser(string username, AuthToken token)
        {
            if (!token.IsAdmin)
            {
                throw new AuthenticationException("Admin must perform this action");
            }

            DbContext context = DataController.CreateDbContext();

            User user = context.Users.FirstOrDefault(u => u.ID == username);

            if (user == null)
            {
                throw new AuthenticationException("User does not exist!");
            }

            if (user.IsAdmin)
            {
                throw new AuthenticationException("Cannot delete the admin user!");
            }

            context.Users.Remove(user);
            context.SaveChanges();
        }