public void GetCodeReturnsCorrectResults()
        {
            var target = new TwoFactorAuth();

            Assert.AreEqual("543160", target.GetCode("VMR466AB62ZBOKHE", 1426847216));
            Assert.AreEqual("538532", target.GetCode("VMR466AB62ZBOKHE", 0));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> EnableAuthenticator([FromBody] EnableAuthenticatorCodeViewModel model)
        {
            try
            {
                // var user = await _userManager.FindByNameAsync(model.UserName);
                var user = await GetCurrentUserAsync();

                if (user != null)
                {
                    TwoFactorAuth TFAuth = new TwoFactorAuth();
                    //sKey = key; //TFAuth.CreateSecret(160);
                    string code = TFAuth.GetCode(user.PhoneNumber);
                    if (model.Code == code)
                    //    bool st = TFAuth.VerifyCode(user.PhoneNumber, model.Code, 5);
                    //if (st)
                    {
                        user.TwoFactorEnabled = true;
                        await _userManager.UpdateAsync(user);

                        return(Ok(new EnableAuthenticationResponse {
                            ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.EnableTwoFactor
                        }));
                    }
                    else
                    {
                        return(BadRequest(new EnableAuthenticationResponse {
                            ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFactorVerification, ErrorCode = enErrorCode.Status4079TwoFAcodeInvalide
                        }));
                    }
                }
                return(BadRequest(new EnableAuthenticationResponse {
                    ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFactorVerification, ErrorCode = enErrorCode.Status4079TwoFAcodeInvalide
                }));

                //var user = await GetCurrentUserAsync();
                //// Strip spaces and hypens
                //var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

                //var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                //    user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);

                //if (!is2faTokenValid)
                //{
                //    return BadRequest(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFactorVerification, ErrorCode = enErrorCode.Status4079TwoFAcodeInvalide });
                //}

                //await _userManager.SetTwoFactorEnabledAsync(user, true);
                //return Ok(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.EnableTwoFactor });
            }
            catch (Exception ex)
            {
                return(BadRequest(new TwoFactorAuthResponse {
                    ReturnCode = enResponseCode.InternalError, ReturnMsg = ex.ToString(), ErrorCode = enErrorCode.Status500InternalServerError
                }));
            }
        }
Exemplo n.º 3
0
        public async Task ConnectUserAsyncWhenInvalidMfa()
        {
            var tfa = new TwoFactorAuth();

            _session.Account.MfaSecret = tfa.CreateSecret();
            await TestHelpers.Instance.AccountDao.TryInsertOrUpdateAsync(_session.Account);

            var result = await _controller.ConnectUserAsync(new ApiSession
            {
                Identity = _session.Account.Name,
                Mfa      = tfa.GetCode(string.Concat(_session.Account.MfaSecret.Reverse())),
            });

            Assert.AreEqual(JsonSerializer.Serialize(new BadRequestObjectResult(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.MFA_INCORRECT))), JsonSerializer.Serialize((BadRequestObjectResult)result));
        }
 public void GetCodeReturnsCorrectResults()
 {
     var target = new TwoFactorAuth();
     Assert.AreEqual("543160", target.GetCode("VMR466AB62ZBOKHE", 1426847216));
     Assert.AreEqual("538532", target.GetCode("VMR466AB62ZBOKHE", 0));
 }
        public void KnownTestVectors_SHA512()
        {
            //Known test vectors for SHA512: https://tools.ietf.org/html/rfc6238#page-15
            var secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA"; //== base32encode('1234567890123456789012345678901234567890123456789012345678901234')
            var target = new TwoFactorAuth(null, 8, 30, Algorithm.SHA512);

            // Test specific timestamps
            Assert.AreEqual("90693936", target.GetCode(secret, 59));
            Assert.AreEqual("25091201", target.GetCode(secret, 1111111109));
            Assert.AreEqual("99943326", target.GetCode(secret, 1111111111));
            Assert.AreEqual("93441116", target.GetCode(secret, 1234567890));
            Assert.AreEqual("38618901", target.GetCode(secret, 2000000000));
            Assert.AreEqual("47863826", target.GetCode(secret, 20000000000));

            // Same values, this time as DateTime instead of timestamp
            Assert.AreEqual("90693936", target.GetCode(secret, new DateTime(1970, 1, 1, 0, 0, 59, DateTimeKind.Utc)));
            Assert.AreEqual("25091201", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 29, DateTimeKind.Utc)));
            Assert.AreEqual("99943326", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 31, DateTimeKind.Utc)));
            Assert.AreEqual("93441116", target.GetCode(secret, new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.AreEqual("38618901", target.GetCode(secret, new DateTime(2033, 5, 18, 3, 33, 20, DateTimeKind.Utc)));
            Assert.AreEqual("47863826", target.GetCode(secret, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));
        }
        public void KnownTestVectors_SHA256()
        {
            //Known test vectors for SHA256: https://tools.ietf.org/html/rfc6238#page-15
            var secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA";   //== base32encode('12345678901234567890123456789012')
            var target = new TwoFactorAuth(null, 8, 30, Algorithm.SHA256);

            // Test specific timestamps
            Assert.AreEqual("46119246", target.GetCode(secret, 59));
            Assert.AreEqual("68084774", target.GetCode(secret, 1111111109));
            Assert.AreEqual("67062674", target.GetCode(secret, 1111111111));
            Assert.AreEqual("91819424", target.GetCode(secret, 1234567890));
            Assert.AreEqual("90698825", target.GetCode(secret, 2000000000));
            Assert.AreEqual("77737706", target.GetCode(secret, 20000000000));

            // Same values, this time as DateTime instead of timestamp
            Assert.AreEqual("46119246", target.GetCode(secret, new DateTime(1970, 1, 1, 0, 0, 59, DateTimeKind.Utc)));
            Assert.AreEqual("68084774", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 29, DateTimeKind.Utc)));
            Assert.AreEqual("67062674", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 31, DateTimeKind.Utc)));
            Assert.AreEqual("91819424", target.GetCode(secret, new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.AreEqual("90698825", target.GetCode(secret, new DateTime(2033, 5, 18, 3, 33, 20, DateTimeKind.Utc)));
            Assert.AreEqual("77737706", target.GetCode(secret, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));
        }
        public void KnownTestVectors_SHA1()
        {
            //Known test vectors for SHA1: https://tools.ietf.org/html/rfc6238#page-15
            var secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";    //== base32encode('12345678901234567890')
            var target = new TwoFactorAuth(null, 8, 30, Algorithm.SHA1);

            // Test specific timestamps
            Assert.AreEqual("94287082", target.GetCode(secret, 59));
            Assert.AreEqual("07081804", target.GetCode(secret, 1111111109));
            Assert.AreEqual("14050471", target.GetCode(secret, 1111111111));
            Assert.AreEqual("89005924", target.GetCode(secret, 1234567890));
            Assert.AreEqual("69279037", target.GetCode(secret, 2000000000));
            Assert.AreEqual("65353130", target.GetCode(secret, 20000000000));

            // Same values, this time as DateTime instead of timestamp
            Assert.AreEqual("94287082", target.GetCode(secret, new DateTime(1970, 1, 1, 0, 0, 59, DateTimeKind.Utc)));
            Assert.AreEqual("07081804", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 29, DateTimeKind.Utc)));
            Assert.AreEqual("14050471", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 31, DateTimeKind.Utc)));
            Assert.AreEqual("89005924", target.GetCode(secret, new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.AreEqual("69279037", target.GetCode(secret, new DateTime(2033, 5, 18, 3, 33, 20, DateTimeKind.Utc)));
            Assert.AreEqual("65353130", target.GetCode(secret, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));
        }
        public void GetCodeThrowsOnInvalidBase32String2()
        {
            var target = new TwoFactorAuth(); 

            target.GetCode("mzxw6==="); // Lowercase
        }
 public void GetCodeThrowsOnInvalidBase32String1()
 {
     var target = new TwoFactorAuth();
     
     target.GetCode("FOO1BAR8BAZ9"); // 1, 8 & 9 are invalid chars
 }
        public void KnownTestVectors_SHA512()
        {
            //Known test vectors for SHA512: https://tools.ietf.org/html/rfc6238#page-15
            var secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNA"; //== base32encode('1234567890123456789012345678901234567890123456789012345678901234')
            var target = new TwoFactorAuth(digits: 8, period: 30, algorithm: Algorithm.SHA512);

            // Test specific timestamps
            Assert.AreEqual("90693936", target.GetCode(secret, 59));
            Assert.AreEqual("25091201", target.GetCode(secret, 1111111109));
            Assert.AreEqual("99943326", target.GetCode(secret, 1111111111));
            Assert.AreEqual("93441116", target.GetCode(secret, 1234567890));
            Assert.AreEqual("38618901", target.GetCode(secret, 2000000000));
            Assert.AreEqual("47863826", target.GetCode(secret, 20000000000));

            // Same values, this time as DateTime instead of timestamp
            Assert.AreEqual("90693936", target.GetCode(secret, new DateTime(1970, 1, 1, 0, 0, 59, DateTimeKind.Utc)));
            Assert.AreEqual("25091201", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 29, DateTimeKind.Utc)));
            Assert.AreEqual("99943326", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 31, DateTimeKind.Utc)));
            Assert.AreEqual("93441116", target.GetCode(secret, new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.AreEqual("38618901", target.GetCode(secret, new DateTime(2033, 5, 18, 3, 33, 20, DateTimeKind.Utc)));
            Assert.AreEqual("47863826", target.GetCode(secret, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));
        }
        public void KnownTestVectors_SHA256()
        {
            //Known test vectors for SHA256: https://tools.ietf.org/html/rfc6238#page-15
            var secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA";   //== base32encode('12345678901234567890123456789012')
            var target = new TwoFactorAuth(digits: 8, period: 30, algorithm: Algorithm.SHA256);

            // Test specific timestamps
            Assert.AreEqual("46119246", target.GetCode(secret, 59));
            Assert.AreEqual("68084774", target.GetCode(secret, 1111111109));
            Assert.AreEqual("67062674", target.GetCode(secret, 1111111111));
            Assert.AreEqual("91819424", target.GetCode(secret, 1234567890));
            Assert.AreEqual("90698825", target.GetCode(secret, 2000000000));
            Assert.AreEqual("77737706", target.GetCode(secret, 20000000000));

            // Same values, this time as DateTime instead of timestamp
            Assert.AreEqual("46119246", target.GetCode(secret, new DateTime(1970, 1, 1, 0, 0, 59, DateTimeKind.Utc)));
            Assert.AreEqual("68084774", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 29, DateTimeKind.Utc)));
            Assert.AreEqual("67062674", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 31, DateTimeKind.Utc)));
            Assert.AreEqual("91819424", target.GetCode(secret, new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.AreEqual("90698825", target.GetCode(secret, new DateTime(2033, 5, 18, 3, 33, 20, DateTimeKind.Utc)));
            Assert.AreEqual("77737706", target.GetCode(secret, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));
        }
        public void KnownTestVectors_SHA1()
        {
            //Known test vectors for SHA1: https://tools.ietf.org/html/rfc6238#page-15
            var secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";    //== base32encode('12345678901234567890')
            var target = new TwoFactorAuth(digits: 8, period: 30, algorithm: Algorithm.SHA1);

            // Test specific timestamps
            Assert.AreEqual("94287082", target.GetCode(secret, 59));
            Assert.AreEqual("07081804", target.GetCode(secret, 1111111109));
            Assert.AreEqual("14050471", target.GetCode(secret, 1111111111));
            Assert.AreEqual("89005924", target.GetCode(secret, 1234567890));
            Assert.AreEqual("69279037", target.GetCode(secret, 2000000000));
            Assert.AreEqual("65353130", target.GetCode(secret, 20000000000));

            // Same values, this time as DateTime instead of timestamp
            Assert.AreEqual("94287082", target.GetCode(secret, new DateTime(1970, 1, 1, 0, 0, 59, DateTimeKind.Utc)));
            Assert.AreEqual("07081804", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 29, DateTimeKind.Utc)));
            Assert.AreEqual("14050471", target.GetCode(secret, new DateTime(2005, 3, 18, 1, 58, 31, DateTimeKind.Utc)));
            Assert.AreEqual("89005924", target.GetCode(secret, new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc)));
            Assert.AreEqual("69279037", target.GetCode(secret, new DateTime(2033, 5, 18, 3, 33, 20, DateTimeKind.Utc)));
            Assert.AreEqual("65353130", target.GetCode(secret, new DateTime(2603, 10, 11, 11, 33, 20, DateTimeKind.Utc)));
        }
        public void GetCodeThrowsOnInvalidBase32String2()
        {
            var target = new TwoFactorAuth();

            target.GetCode("mzxw6==="); // Lowercase
        }
        public void GetCodeThrowsOnInvalidBase32String1()
        {
            var target = new TwoFactorAuth();

            target.GetCode("FOO1BAR8BAZ9"); // 1, 8 & 9 are invalid chars
        }
Exemplo n.º 15
0
        public async Task <IActionResult> twoFaAuth(csgo.postModels.twoFactor obj)
        {
            if (csgo.Controllers.adminController.tokenAccess.validateToken(Request, adminController.tokenType.twofactor))
            {
                if (csgo.core.requestsHelper.processRequest(Request))
                {
                    return(Json(new { success = "false", message = "You are sending to many requests. Blacklist will expire in 30 seconds." }));
                }
                var a = TempData["userId"];
                if (a == null)
                {
                    TempData["toast"] = "{type:'error',message:'You are not authorized. An error occured try again later 1.'}";
                    return(this.Redirect(@Url.Action("index", "home")));
                }
                int userId       = (int)a;
                var temp2FAToken = TempData["temp2FAToken"];
                if (temp2FAToken != null)
                {
                    if (obj.code != null && tfa.VerifyCode((string)temp2FAToken, obj.code.Replace(" ", "")))
                    {
                        await databaseManager.updateQuery($"UPDATE users SET twofaToken = '{temp2FAToken}', loginIP = '' WHERE id = @id LIMIT 1").addValue("@id", TempData["userId"]).Execute();

                        TempData["toast"] = "{type:'success',message:'You successully configured the authentificator.'}";
                        return(this.Redirect(@Url.Action("index", "login")));
                    }
                    else
                    {
                        TempData["userId"] = (int)userId;


                        TempData["temp2FAToken"] = (string)temp2FAToken;
                        TempData["token2FA"]     = "";
                        csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.twofactor);
                        return(this.Redirect("https://localhost/2fa"));
                    }
                }
                var token2FA = TempData["token2FA"];
                if (token2FA == null)
                {
                    TempData["toast"] = "{type:'error',message:'You are not authorized.'}";
                    return(this.Redirect(@Url.Action("index", "home")));
                }
                Console.WriteLine($"TOKEN FROM DATABASE {(string)token2FA} AND CODE {obj.code} TIME ON THE SERVER {DateTime.Now}");
                Console.WriteLine($"TOKEN SERVERSIDE {tfa.GetCode((string)token2FA, tfa.TimeProvider.GetTimeAsync().Result)}");
                Console.WriteLine(tfa.VerifyCode((string)token2FA, obj.code, 1, DateTime.UtcNow));
                Console.WriteLine($"UTC NOW {DateTime.UtcNow.ToString()}");
                Console.WriteLine($"GENERATED 2FA CODE {tfa.GetCode((string)token2FA)}");
                if (tfa.VerifyCode((string)token2FA, obj.code.Replace(" ", "")))
                {
                    Guid   g          = Guid.NewGuid();
                    string GuidString = Convert.ToBase64String(g.ToByteArray());
                    GuidString = GuidString.Replace("=", "");
                    GuidString = GuidString.Replace("+", "");

                    string cookiegenerated = GuidString;
                    string ip = Request.getIPAddress();

                    userData userDetails = new userData();
                    userDetails.loginIP = ip;
                    await databaseManager.selectQuery("SELECT * FROM users WHERE id = @id LIMIT 1", delegate(DbDataReader reader)
                    {
                        if (reader.HasRows)
                        {
                            userDetails.balance        = (decimal)reader["balance"];
                            userDetails.username       = (string)reader["username"];
                            userDetails.id             = (int)reader["id"];
                            userDetails.cookie         = cookiegenerated;
                            userDetails.registerDate   = (DateTime)reader["registerDate"];
                            userDetails.seller         = (bool)reader["seller"];
                            userDetails.negativeRates  = (int)reader["negativeRates"];
                            userDetails.positiveRates  = (int)reader["positiveRates"];
                            userDetails.soldAccounts   = (int)reader["soldAccounts"];
                            userDetails.boughtAccounts = (int)reader["boughtAccounts"];
                            userDetails.confirmed      = (bool)reader["confirmed"];
                            userDetails.admin          = (bool)reader["admin"];
                            userDetails.email          = (string)reader["email"];
                            userDetails.lastConfirm    = (DateTime)reader["lastConfirm"];
                            userDetails.validateToken  = (string)reader["validateToken"];
                            userDetails.lastUpdate     = DateTime.Now;
                            userDetails.banned         = (bool)reader["banned"];
                            userDetails.banReason      = (string)reader["banReason"];
                            userDetails.twofa          = (bool)reader["twofa"];
                            userDetails.twofaToken     = (string)reader["twofaToken"];
                            userDetails.lastLogin      = (DateTime)reader["lastLogin"];
                        }
                    }).addValue("@id", userId).Execute();

                    if (userDetails.banned)
                    {
                        TempData["toast"] = "{type:'error',message:'" + $"Your account is banned on this site. Reason: {userDetails.banReason}" + "'}";
                        return(this.Redirect(@Url.Action("index", "home")));
                    }

                    if (!userDetails.confirmed)
                    {
                        if (userDetails.email.Contains("yahoo"))
                        {
                            TempData["toast"]  = "{type:'warning',message:'Yahoo isn't fully supported. Please change your email in order to use this site.'}";
                            TempData["userId"] = userDetails.id;
                            Console.WriteLine("email recovery");
                            csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.changeemail);
                            return(this.Redirect(@Url.Action("changeEmail")));
                        }
                        else
                        {
                            if ((int)(DateTime.Now - userDetails.lastConfirm).TotalMinutes > 30)
                            {
                                if (userDetails.validateToken.Length < 3)
                                {
                                    userDetails.validateToken = csgo.core.emailManager.randomToken(new Random().Next(10, 30));
                                }
                                Console.WriteLine(csgo.core.emailManager.sendConfirmationEmail(userDetails.email, userDetails.validateToken).Content);
                                await databaseManager.updateQuery($"UPDATE users SET lastConfirm = CURRENT_TIMESTAMP, validateToken = @validateToken WHERE id = @id LIMIT 1").addValue("@validateToken", userDetails.validateToken).addValue("@id", userId).Execute();

                                TempData["toast"] = "{type:'success',message:'And confirmation code was send to your email.'}";
                            }
                            else
                            {
                                TempData["toast"] = "{type:'success',message:'Account isn`t confirmed yet. Check your email.'}";
                            }
                        }
                        return(this.Redirect(@Url.Action("index", "home")));
                    }

                    CookieOptions option = new CookieOptions();



                    option.Expires = new DateTimeOffset?(DateTime.Now.AddDays(5));

                    Response.Cookies.Append("sessionid", cookiegenerated, option);

                    await databaseManager.updateQuery($"UPDATE users SET cookie = '{cookiegenerated}', loginIP = '{ip}', lastLogin = CURRENT_TIMESTAMP WHERE id = @id LIMIT 1").addValue("@id", userId).Execute();

                    var index = csgo.usersManager.users.FindIndex(a => a.id == userId);

                    if (index != -1)
                    {
                        var b = csgo.usersManager.users[index];
                        if (b.connectionId != null)
                        {
                            await b.sendNotify(core.notifyManager.notifyType.warning, $"Someone just connected on your account using 2FA. IP: {ip}. You will be log out.");

                            await csgo.core.ChatHub.Current.Clients.Client(b.connectionId).SendAsync("logout");
                        }
                        csgo.usersManager.users[index] = userDetails;
                    }
                    else
                    {
                        csgo.usersManager.users.Add(userDetails);
                    }

                    var s = TempData["loginRequest"];

                    TempData.Remove("loginRequest");
                    TempData["toast"] = "{type:'success',message:'You succesfully logged in using 2FA.'}";

                    return(this.Redirect(@Url.Action("index", "home")));
                }
                else
                {
                    TempData["userId"]   = (int)userId;
                    TempData["token2FA"] = (string)token2FA;
                    TempData["toast"]    = "{type:'error',message:'Your 2FA code is invalid. You have more 2 chances.'}";
                    csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.twofactor);
                    return(this.Redirect("https://localhost/2fa/"));
                }



                TempData["toast"] = "{type:'success',message:'And confirmation code was send to your new email.'}";
                return(this.Redirect(@Url.Action("index", "home")));
            }
            TempData["toast"] = "{type:'error',message:'You are not authorized 2.'}";
            return(this.Redirect(@Url.Action("index", "home")));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> Disable2fa([FromBody] DisableAuthenticatorViewModel model)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                if (!user.TwoFactorEnabled)
                {
                    return(BadRequest(new DisableAuthenticatorResponse {
                        ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFAalreadyDisable, ErrorCode = enErrorCode.Status4108TwoFAalreadydisable
                    }));
                }

                TwoFactorAuth TFAuth = new TwoFactorAuth();
                //sKey = key; //TFAuth.CreateSecret(160);
                string code = TFAuth.GetCode(user.PhoneNumber);
                if (model.Code != code)
                //    bool status = TFAuth.VerifyCode(user.PhoneNumber, model.Code, 5);
                //if (!status)
                {
                    return(BadRequest(new DisableAuthenticatorResponse {
                        ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFactorVerificationDisable, ErrorCode = enErrorCode.Status4071TwoFactorVerificationDisable
                    }));
                }
                else
                {
                    //user.TwoFactorEnabled = true;
                    //await _userManager.UpdateAsync(user);
                    var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);

                    //return Ok(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.EnableTwoFactor });
                    if (disable2faResult.Succeeded)
                    {
                        string oldvalue = JsonConvert.SerializeObject(user);
                        user.TwoFactorEnabled = false;
                        await _userManager.UpdateAsync(user);

                        string Newvalue = JsonConvert.SerializeObject(user);
                        UserChangeLogViewModel userChangeLogViewModel = new UserChangeLogViewModel();
                        userChangeLogViewModel.Id       = user.Id;
                        userChangeLogViewModel.Newvalue = Newvalue;
                        userChangeLogViewModel.Type     = EnuserChangeLog.TwofactoreChange.ToString();
                        userChangeLogViewModel.Oldvalue = oldvalue;

                        long userlog = _iuserChangeLog.AddPassword(userChangeLogViewModel);
                        //_logger.LogInformation("User with ID {UserId} has disabled 2fa.", user.Id);
                        return(Ok(new DisableAuthenticatorResponse {
                            ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.DisableTroFactor
                        }));
                    }
                    else
                    {
                        return(BadRequest(new DisableAuthenticatorResponse {
                            ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.DisableTroFactorError, ErrorCode = enErrorCode.Status4055DisableTroFactorError
                        }));
                    }
                }



                /*
                 * // Strip spaces and hypens
                 * var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
                 *
                 * var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                 *  user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
                 *
                 * if (!is2faTokenValid)
                 * {
                 *  return BadRequest(new DisableAuthenticatorResponse { ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFactorVerificationDisable, ErrorCode = enErrorCode.Status4071TwoFactorVerificationDisable });
                 *
                 * }
                 * else
                 * {
                 *  var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
                 *  if (disable2faResult.Succeeded)
                 *  {
                 *      string oldvalue = JsonConvert.SerializeObject(user);
                 *      user.TwoFactorEnabled = false;
                 *      await _userManager.UpdateAsync(user);
                 *      string Newvalue = JsonConvert.SerializeObject(user);
                 *      UserChangeLogViewModel userChangeLogViewModel = new UserChangeLogViewModel();
                 *      userChangeLogViewModel.Id = user.Id;
                 *      userChangeLogViewModel.Newvalue = Newvalue;
                 *      userChangeLogViewModel.Type = EnuserChangeLog.TwofactoreChange.ToString();
                 *      userChangeLogViewModel.Oldvalue = oldvalue;
                 *
                 *      long userlog = _iuserChangeLog.AddPassword(userChangeLogViewModel);
                 *      _logger.LogInformation("User with ID {UserId} has disabled 2fa.", user.Id);
                 *      return Ok(new DisableAuthenticatorResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.DisableTroFactor });
                 *  }
                 *  else
                 *  {
                 *      return BadRequest(new DisableAuthenticatorResponse { ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.DisableTroFactorError, ErrorCode = enErrorCode.Status4055DisableTroFactorError });
                 *  }
                 * }
                 */
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Date: " + _basePage.UTC_To_IST() + ",\nMethodName:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\nControllername=" + this.GetType().Name, LogLevel.Error);
                return(BadRequest(new DisableAuthenticatorResponse {
                    ReturnCode = enResponseCode.InternalError, ReturnMsg = ex.ToString(), ErrorCode = enErrorCode.Status500InternalServerError
                }));
            }
        }