public static ParamContainer CreateParamContainer(ILogger loggerController, IActionExecuter actionExecuter)
        {
            ILogReader         logReader         = Logger.GetLogReader();
            IAppSettingService appSettingService = AppSettingService.Instance;
            ParamContainer     paramContainer    = new ParamContainer();

            IDBService       dbService       = ApplicationConfig.DependencyResolver.GetInstance <IDBService>();
            IPingService     pingService     = ApplicationConfig.DependencyResolver.GetInstance <IPingService>();
            IViewEngine      viewEngine      = ApplicationConfig.DependencyResolver.GetInstance <IViewEngine>();
            IEncryption      encryption      = ApplicationConfig.DependencyResolver.GetInstance <IEncryption>();
            IKeyValueStorage keyValueStorage = ApplicationConfig.DependencyResolver.GetInstance <IKeyValueStorage>();

            ISMSService   smsService   = new SMSService(loggerController, dbService, actionExecuter, viewEngine, paramContainer);
            IEmailService emailService = new EmailService(loggerController, dbService, actionExecuter, viewEngine, paramContainer);
            IOTPService   otpService   = new OTPService(loggerController, dbService, smsService, emailService, appSettingService);

            paramContainer.AddKey(CommonConst.CommonValue.PARAM_DBPROXY, () => { return(dbService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_LOGGER, () => { return(loggerController); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_ACTIONEXECUTER, () => { return(actionExecuter); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_PING_SERVICE, () => { return(pingService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_PING_SERVICE, () => { return(pingService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_APP_SETTING, () => { return(appSettingService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_VIEW_ENGINE, () => { return(viewEngine); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_OTP_SERVICE, () => { return(otpService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_SMS_SERVICE, () => { return(smsService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_EMAIL_SERVICE, () => { return(emailService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_ENCRYPTION_SERVICE, () => { return(encryption); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_KEY_VALUE_STORAGE, () => { return(keyValueStorage); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_HTTP_CLIENT, () => { return(new HttpRestClient()); });

            return(paramContainer);
        }
        public void Setup()
        {
            _otpAlgorithm          = MockRepository.GenerateMock <IOTPAlgorithm>();
            _movingFactorAlgorithm = MockRepository.GenerateMock <IMovingFactorAlgorithm>();
            _errorFactory          = MockRepository.GenerateMock <IErrorFactory>();
            _otpConfiguration      = new OTPConfiguration
            {
                OTPExpiryInSeconds  = 31,
                NumberOfDigitsInOTP = 6,
                PrivateKey          = "as9121jd623ms23h232k3"
            };
            _otpService          = new OTPService(_otpAlgorithm, _movingFactorAlgorithm, _errorFactory, _otpConfiguration);
            _invalidRequestError = new OTPError
            {
                Code        = "InvalidRequest",
                Description = "Please check your request and try again."
            };
            _errorFactory.Stub(factory => factory.GetInvalidRequestError()).Return(_invalidRequestError);

            _genericError = new OTPError
            {
                Code        = "InternalError",
                Description = "Something went wrong, please try again later."
            };
            _errorFactory.Stub(factory => factory.GetErrorForException(null)).IgnoreArguments().Return(_genericError);
        }
Example #3
0
        JObject ProcessOtpRequest(RequestInfo requestInfo)
        {
            // check
            if (requestInfo.Extra == null)
            {
                throw new InvalidRequestException();
            }

            // prepare
            var id    = requestInfo.Extra.ContainsKey("ID") ? requestInfo.Extra["ID"].Decrypt(this.EncryptionKey) : "";
            var stamp = requestInfo.Extra.ContainsKey("Stamp") ? requestInfo.Extra["Stamp"].Decrypt(this.EncryptionKey) : "";

            var key      = $"{id}@{stamp}".ToLower().GetHMACHash(this.AuthenticationKey.ToBytes(), "SHA512");
            var response = new JObject();

            // setup for provisioning
            if (requestInfo.Extra.ContainsKey("Setup"))
            {
                var account = requestInfo.Extra.ContainsKey("Account") ? requestInfo.Extra["Account"].Decrypt(this.EncryptionKey) : "";
                var issuer  = requestInfo.Extra.ContainsKey("Issuer") ? requestInfo.Extra["Issuer"].Decrypt(this.EncryptionKey) : "";
                if (string.IsNullOrWhiteSpace(issuer))
                {
                    issuer = UtilityService.GetAppSetting("OTPs:Issuer", "VIEApps NGX");
                }
                var size            = requestInfo.Extra.ContainsKey("Size") ? requestInfo.Extra["Size"].CastAs <int>() : UtilityService.GetAppSetting("OTPs:QRCode-Size", "300").CastAs <int>();
                var ecl             = requestInfo.Extra.ContainsKey("ECCLevel") ? requestInfo.Extra["ECCLevel"] : UtilityService.GetAppSetting("OTPs:QRCode-ECCLevel", "L");
                var provisioningUri = OTPService.GenerateProvisioningUri(account, key, issuer.UrlEncode());

                response["URI"] = this.GetHttpURI("Files", "https://fs.vieapps.net")
                                  + $"/qrcodes/{UtilityService.NewUUID.Encrypt(null, true).Substring(UtilityService.GetRandomNumber(13, 43), 13)}"
                                  + $"?v={provisioningUri.Encrypt(this.EncryptionKey).ToBase64Url(true)}"
                                  + $"&t={DateTime.Now.ToUnixTimestamp().ToString().Encrypt(this.EncryptionKey).ToBase64Url(true)}"
                                  + $"&s={size}&ecl={ecl}";
            }

            // validate input of client
            else
            {
                var password = requestInfo.Extra.ContainsKey("Password") ? requestInfo.Extra["Password"].Decrypt(this.EncryptionKey) : "";
                if (string.IsNullOrWhiteSpace(password))
                {
                    throw new OTPLoginFailedException();
                }

                var interval = "App".IsEquals(requestInfo.Extra.ContainsKey("Type") ? requestInfo.Extra["Type"] : "App") ? 30 : 300;
                if (!password.Equals(OTPService.GeneratePassword(key, interval)))
                {
                    throw new OTPLoginFailedException();
                }
            }

            // response
            return(response);
        }
Example #4
0
        public void CTOR_NullSettings_ThrowsArgumentNullException()
        {
            // arrange
            var sut = new OTPService(null, null, null);

            // act
            sut.GenerateOTP(null);

            // assert
            Assert.Fail();
        }
Example #5
0
        public void CTOR_NullHotpToByteConverter_ThrowsArgumentNullException()
        {
            // arrange
            var sut = new OTPService(Mock.Of <ISettings>(), null, null);

            // act
            sut.GenerateOTP(null);

            // assert
            Assert.Fail();
        }
        private string GetValidOTP(string userId)
        {
            var otpService = new OTPService(new HmacBasedOTPAlgorithm(),
                                            new ExpiryBasedMovingFactorAlgorithm(new OTPConfiguration()), new ErrorFactory(), new OTPConfiguration());
            var generateOtpRequest = new GenerateOTPRequest {
                UserId = userId
            };
            GenerateOTPResponse generateOTPResponse = otpService.GenerateOtp(generateOtpRequest);

            return(generateOTPResponse.OTP);
        }
Example #7
0
        public void CTOR_NullSecretGeneratorProvider_ThrowsArgumentNullException()
        {
            // arrange
            var sut = new OTPService(Mock.Of <ISettings>(),
                                     Mock.Of <IOneWayConverter <long, byte[]> >(), null);

            // act
            sut.GenerateOTP(null);

            // assert
            Assert.Fail();
        }
Example #8
0
        public JObject SendForgetpassOTP()
        {
            Logger.Debug("Calling SendForgetpassOTP");
            JObject request = HttpProxy.GetRequestBody <JObject>();

            if (request == null)
            {
                return(ResponseBuilder.CreateReponse(CommonConst._400_BAD_REQUEST));
            }

            Logger.Debug("Request body SendForgetpassOTP", request);
            UserModel requestUser       = GetUserDataFromRequest(request);
            var       recaptchaResponse = request[ModuleAppConsts.Field.GOOGLE_RECAPTCHA_RESPONSE_KEY].ToString();
            var       capchaChecked     = SessionProvider.GetValue <bool>(USER_REGISTRATION_CAPCHA_VALIDATION_SESSION_KEY);

            if (capchaChecked && !GoogleCaptchaHelper.ValidateResponse(Logger, recaptchaResponse, AppSettingService.GetAppSettingData(ModuleAppConsts.Field.GOOGLE_RECAPTCHA_SECRECT_SETTING_KEY), AppSettingService.GetAppSettingData(ModuleAppConsts.Field.GOOGLE_RECAPTCHA_VALIDATE_URL_SETTING_KEY)))
            {
                Logger.Info("Captcha validate fail SendForgetpassOTP");
                return(ResponseBuilder.CreateReponse(AppResponseCode._CAPTCHA_VALIDATION_FAIL));
            }
            else
            {
                SessionProvider.SetValue <bool>(USER_REGISTRATION_CAPCHA_VALIDATION_SESSION_KEY, true);
            }
            if (IsUserExists(requestUser.user_id))
            {
                string securityToken = CommonUtility.RandomString(10);
                if (requestUser.user_type == UserIDType.PhoneNumber.ToString() && OTPService.Send(requestUser.user_id, ModuleAppConsts.Field.FORGET_PASS_OTP_SMS_TEMPLATE, OTPType.Forgetpassword, securityToken))
                {
                    JObject dataResponse = new JObject();
                    dataResponse[CommonConst.CommonField.SECURITY_TOKEN] = securityToken;
                    SessionProvider.SetValue <UserModel>(CommonConst.CommonValue.SIGN_UP_SESSION_USER_KEY, requestUser);

                    return(ResponseBuilder.CreateReponse(CommonConst._1_SUCCESS, null, dataResponse));
                }
                else if (requestUser.user_type == UserIDType.Email.ToString() && OTPService.SendEmail(requestUser.user_id, ModuleAppConsts.Field.FORGET_PASS_OTP_EMAIL_TEMPLATE, AppSettingService.GetAppSettingData(ModuleAppConsts.Field.FORGET_PASS_OTP_EMAIL_SUBJECT), OTPType.Forgetpassword, securityToken))
                {
                    JObject dataResponse = new JObject();
                    dataResponse[CommonConst.CommonField.SECURITY_TOKEN] = securityToken;

                    SessionProvider.SetValue <UserModel>(CommonConst.CommonValue.SIGN_UP_SESSION_USER_KEY, requestUser);
                    return(ResponseBuilder.CreateReponse(CommonConst._1_SUCCESS, null, dataResponse));
                }
                else
                {
                    return(ResponseBuilder.CreateReponse(AppResponseCode._OTP_SEND_ERROR));
                }
            }
            else
            {
                return(ResponseBuilder.CreateReponse(AppResponseCode._USER_NOT_FOUND));
            }
        }
        public void Setup()
        {
            var otpConfiguration = new OTPConfiguration
            {
                OTPExpiryInSeconds  = 31,
                NumberOfDigitsInOTP = 6,
                PrivateKey          = "as9121jd623ms23h232k3"
            };

            _otpService = new OTPService(new HmacBasedOTPAlgorithm(),
                                         new ExpiryBasedMovingFactorAlgorithm(otpConfiguration), new ErrorFactory(),
                                         otpConfiguration);
        }
        public async Task <IActionResult> GetAsync(string sessionID, string code)
        {
            OTPService service  = new OTPService();
            var        response = await service.VerifyOTPAsync("username", "password", "url", sessionID, code);

            //check code value
            if (true)
            {
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
        public async Task <IActionResult> PostAsync(string phoneNumber)
        {
            string     sessionID = string.Empty;
            OTPService service   = new OTPService();
            var        response  = await service.GenerateOTPAsync("username", "password", "url", phoneNumber);

            //check sessionID value
            if (true)
            {
                return(Ok(sessionID));
            }
            else
            {
                return(BadRequest());
            }
        }
Example #12
0
        public JObject ValidateOTP()
        {
            Logger.Debug("Calling ValidateOTP");
            JObject request = HttpProxy.GetRequestBody <JObject>();

            if (request == null)
            {
                return(ResponseBuilder.CreateReponse(CommonConst._400_BAD_REQUEST));
            }

            var       otp           = request[CommonConst.CommonField.OTP].ToString();
            UserModel requestUser   = GetUserDataFromRequest(request);
            var       securityToken = request[CommonConst.CommonField.SECURITY_TOKEN].ToString();

            if (!IsUserExists(requestUser.user_id))
            {
                if (requestUser.user_type == UserIDType.PhoneNumber.ToString() && OTPService.Validate(requestUser.user_id, otp, OTPType.Signup, securityToken))
                {
                    UserModel tempUser = new UserModel()
                    {
                        user_id = requestUser.user_id, user_type = UserIDType.PhoneNumber.ToString()
                    };
                    SessionProvider.SetValue(CommonConst.CommonValue.SIGN_UP_SESSION_USER_KEY, tempUser);
                    return(ResponseBuilder.CreateReponse(CommonConst._1_SUCCESS));
                }
                else if (requestUser.user_type == UserIDType.Email.ToString() && OTPService.ValidateEmail(requestUser.user_id, otp, OTPType.Signup, securityToken))
                {
                    UserModel tempUser = new UserModel()
                    {
                        user_id = requestUser.user_id, user_type = UserIDType.Email.ToString()
                    };
                    SessionProvider.SetValue(CommonConst.CommonValue.SIGN_UP_SESSION_USER_KEY, tempUser);
                    return(ResponseBuilder.CreateReponse(CommonConst._1_SUCCESS));
                }
                else
                {
                    Logger.Error("Error OTP validation fail");
                    return(ResponseBuilder.CreateReponse(AppResponseCode._OTP_VALIDATION_FAIL));
                }
            }
            else
            {
                Logger.Info(string.Format("User Exits with this phone number {0}", requestUser.user_id));
                return(ResponseBuilder.CreateReponse(AppResponseCode._USER_EXISTS));
            }
        }
Example #13
0
        public void GenerateOTP_SecretGenerator_SecretIsGeneratedUsingUserId()
        {
            // arrange
            var secretGeneratorMock = new Mock <ISecretGeneratorProvider>();
            var userId       = "some user id";
            var userIdBase64 = "c29tZSB1c2VyIGlk";

            secretGeneratorMock.Setup(x => x.GenerateSecret(userId)).Returns(userIdBase64);
            var sut = new OTPService(this.MockSettings().Object,
                                     Mock.Of <IOneWayConverter <long, byte[]> >(), secretGeneratorMock.Object);

            // act
            sut.GenerateOTP(userId);

            // assert
            secretGeneratorMock.Verify(x => x.GenerateSecret(userId), Times.Once);
        }
Example #14
0
        public IActionResult VerifyOTP([FromQuery] string username, string otp)
        {
            OTPService service = new OTPService(configuration.GetConnectionString("MAF"));

            try
            {
                if (!service.VerifyOTP(username, otp))
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
Example #15
0
        public void GenerateOTP_Settings_MakesUserOfTimeStep()
        {
            // arrange
            var secretGeneratorMock = new Mock <ISecretGeneratorProvider>();
            var userId       = "some user id";
            var userIdBase64 = "c29tZSB1c2VyIGlk";
            var settingsMock = this.MockSettings();

            secretGeneratorMock.Setup(x => x.GenerateSecret(userId)).Returns(userIdBase64);
            var sut = new OTPService(settingsMock.Object,
                                     Mock.Of <IOneWayConverter <long, byte[]> >(), secretGeneratorMock.Object);

            // act
            sut.GenerateOTP(userId);

            // assert
            settingsMock.VerifyGet(x => x.TimeStep, Times.AtLeastOnce());
        }
Example #16
0
        public IActionResult ResendOTP([FromQuery] string username)
        {
            OTPService service = new OTPService(configuration.GetConnectionString("MAF"));
            MobileOTP  oTP;

            try
            {
                oTP = service.GetOTP(username);
                SMSHelper helper = new SMSHelper(configuration);
                helper.Send(oTP.MobileNo, oTP.OTP);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
Example #17
0
        public IActionResult GenerateOTP([FromBody] OTPRequest request)
        {
            OTPService service = new OTPService(configuration.GetConnectionString("MAF"));
            MobileOTP  oTP;

            try
            {
                oTP = service.GenerateOTP(request);
                SMSHelper helper = new SMSHelper(configuration);
                helper.Send(oTP.MobileNo, oTP.OTP);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
Example #18
0
        public void GenerateOTP_ValidInput_GeneratesValidOTPResult()
        {
            // arrange
            var secretGeneratorMock = new Mock <ISecretGeneratorProvider>();
            var userId            = "some user id";
            var userIdBase64      = "c29tZSB1c2VyIGlk";
            var settingsMock      = this.MockSettings();
            var dateTime          = new DateTime(2020, 1, 1, 0, 0, 1);
            var hotpByteConverter = new Mock <IOneWayConverter <long, byte[]> >();

            secretGeneratorMock.Setup(x => x.GenerateSecret(userId)).Returns(userIdBase64);
            var sut = new OTPService(settingsMock.Object, hotpByteConverter.Object, secretGeneratorMock.Object);

            // act
            var result = sut.GenerateOTP(userId, dateTime);

            // assert
            Assert.IsNotNull(result);
        }
Example #19
0
        public void GenerateOTP_HotpToByteConverter_CovnertsBytes()
        {
            // arrange
            var secretGeneratorMock = new Mock <ISecretGeneratorProvider>();
            var userId            = "some user id";
            var userIdBase64      = "c29tZSB1c2VyIGlk";
            var settingsMock      = this.MockSettings();
            var dateTime          = new DateTime(2020, 1, 1, 0, 0, 1);
            var hotpByteConverter = new Mock <IOneWayConverter <long, byte[]> >();
            var hotpValue         = 52594560L;

            secretGeneratorMock.Setup(x => x.GenerateSecret(userId)).Returns(userIdBase64);
            var sut = new OTPService(settingsMock.Object, hotpByteConverter.Object, secretGeneratorMock.Object);

            // act
            sut.GenerateOTP(userId, dateTime);

            // assert
            hotpByteConverter.Verify(x => x.Convert(hotpValue), Times.Once());
        }
Example #20
0
 public OtpController(IConfiguration configuration)
 {
     otpService = new OTPService(configuration);
 }
Example #21
0
 //Prints a random OTP string without creating the object
 public string GetRandomOTP()
 {
     return(OTPService.RandomString(64));
 }
Example #22
0
        public JObject ResetPassword()
        {
            try
            {
                Logger.Debug("Calling ResetPassword");
                JObject request = HttpProxy.GetRequestBody <JObject>();
                Logger.Debug("ResetPassword Request data", request);

                var redirect_url = HttpProxy.GetQueryString(CommonConst.CommonField.REDIRECT_URL_KEY);
                if (request == null)
                {
                    return(ResponseBuilder.CreateReponse(CommonConst._400_BAD_REQUEST));
                }
                var otp                = request[CommonConst.CommonField.OTP].ToString();
                var requestUser        = GetUserDataFromRequest(request);
                var forgetpasswordUser = SessionProvider.GetValue <UserModel>(CommonConst.CommonValue.SIGN_UP_SESSION_USER_KEY);
                if (forgetpasswordUser == null)
                {
                    return(ResponseBuilder.CreateReponse(AppResponseCode._SESSION_USER_NOT_FOUND));
                }
                if (forgetpasswordUser.user_id != requestUser.user_id)
                {
                    return(ResponseBuilder.CreateReponse(AppResponseCode._SESSION_USER_DATA_MISMATCH));
                }

                if (request[CommonConst.CommonField.PASSWORD].ToString() != request[CommonConst.CommonField.CONFIRM_PASSWORD].ToString())
                {
                    return(ResponseBuilder.CreateReponse(AppResponseCode._SESSION_USER_DATA_MISMATCH));
                }

                var capchaChecked = SessionProvider.GetValue <bool>(USER_REGISTRATION_CAPCHA_VALIDATION_SESSION_KEY);

                if (!capchaChecked)
                {
                    Logger.Info("Captcha validate fail");
                    return(ResponseBuilder.CreateReponse(AppResponseCode._CAPTCHA_VALIDATION_FAIL));
                }

                bool OTPValidate = false;
                if (requestUser.user_type == UserIDType.PhoneNumber.ToString() && OTPService.Validate(requestUser.user_id, otp, OTPType.Forgetpassword, string.Empty))
                {
                    OTPValidate = true;
                }
                else if (requestUser.user_type == UserIDType.Email.ToString() && OTPService.ValidateEmail(requestUser.user_id, otp, OTPType.Forgetpassword, string.Empty))
                {
                    OTPValidate = true;
                }
                else
                {
                    Logger.Error("Error OTP validation fail");
                    return(ResponseBuilder.CreateReponse(AppResponseCode._OTP_VALIDATION_FAIL));
                }

                if (ResetPass(requestUser, request[CommonConst.CommonField.PASSWORD].ToString()) && OTPValidate)
                {
                    var user = DBProxy.FirstOrDefault <UserModel>(CommonConst.Collection.USERS, CommonConst.CommonField.USER_ID, requestUser.user_id);

                    var     rurl        = AppSettingService.GetAppSettingData(ModuleAppConsts.Field.FORGET_PASS_LENDING_PAGE_SETTING_KEY);
                    JObject resonseData = new JObject();
                    if (string.IsNullOrEmpty(redirect_url))
                    {
                        resonseData[CommonConst.CommonField.REDIRECT_URL_KEY] = rurl;
                    }
                    else
                    {
                        resonseData[CommonConst.CommonField.REDIRECT_URL_KEY] = string.Format("{0}?{1}={2}", rurl, CommonConst.CommonField.REDIRECT_URL_KEY, redirect_url);
                    }
                    return(ResponseBuilder.CreateReponse(CommonConst._1_SUCCESS, null, resonseData));
                }
                else
                {
                    Logger.Error("Error while ResetPassword");
                    return(ResponseBuilder.CreateReponse(CommonConst._500_SERVER_ERROR));
                }
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("Forgetpassword.ResetPassword error : {0}", ex.Message), ex);
                return(ResponseBuilder.CreateReponse(CommonConst._500_SERVER_ERROR));
            }
        }