public static bool ValidateAuthCode(this UserInfo user, string code, bool checkBackup = true)
        {
            if (!TfaAppAuthSettings.IsVisibleSettings ||
                !TfaAppAuthSettings.Enable)
            {
                return(false);
            }

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }

            code = (code ?? "").Trim();

            if (string.IsNullOrEmpty(code))
            {
                throw new Exception(Resource.ActivateTfaAppEmptyCode);
            }

            int counter;

            int.TryParse(Cache.Get <string>("tfa/" + user.ID), out counter);
            if (++counter > SetupInfo.LoginThreshold)
            {
                throw new Authorize.BruteForceCredentialException(Resource.TfaTooMuchError);
            }
            Cache.Insert("tfa/" + user.ID, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!Tfa.ValidateTwoFactorPIN(GenerateAccessToken(user), code))
            {
                if (checkBackup && TfaAppUserSettings.BackupCodesForUser(user.ID).Any(x => x.Code == code && !x.IsUsed))
                {
                    TfaAppUserSettings.DisableCodeForUser(user.ID, code);
                }
                else
                {
                    throw new ArgumentException(Resource.TfaAppAuthMessageError);
                }
            }

            Cache.Insert("tfa/" + user.ID, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!SecurityContext.IsAuthenticated)
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }

            if (!TfaAppUserSettings.EnableForUser(user.ID))
            {
                user.GenerateBackupCodes();
                return(true);
            }

            return(false);
        }
Пример #2
0
        private string GenerateAccessToken(UserInfo user)
        {
            var userSalt = TfaAppUserSettings.GetSalt(SettingsManager, user.ID);

            //from Signature.Create
            var machineSalt  = Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant());
            var token        = Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(userSalt + machineSalt)));
            var encodedToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));

            return(encodedToken.Substring(0, 10));
        }
 private static string GenerateAccessToken(UserInfo user)
 {
     return(Signature.Create(TfaAppUserSettings.GetSalt(user.ID)).Substring(0, 10));
 }