예제 #1
0
        public SetupCode GetScanCode()
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            SetupCode setupInfo        = tfa.GenerateSetupCode("Test", "*****@*****.**", userSecretKey, 300, 300);

            return(setupInfo);
        }
예제 #2
0
 public ActionResult validateSms(string phoneCode)
 {
     try
     {
         if (Session["phoneCode"].ToString() == phoneCode)
         {
             ViewData["step"] = "third";
             ViewBag.Action   = "google_auth";
             AzureConnection db        = new AzureConnection();
             string          email     = Session["email"].ToString();
             var             user_data = db.user_table.Where(a => a.email == email).FirstOrDefault();
             user_data.qrScanned = true;
             db.SaveChanges();
             TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
             SetupCode setupInfo        = tfa.GenerateSetupCode("TRUSTBTC", Session["email"].ToString(), Session["qrkey"].ToString(), 300, 300);
             ViewData["qrUrl"] = setupInfo.QrCodeSetupImageUrl;
             return(View("google_auth"));
         }
         else
         {
             ViewData["step"] = "second";
             ViewBag.Action   = "google_auth";
             ViewBag.Message  = "Code isn't correct.";
             return(View("google_auth"));
         }
     }
     catch
     {
         return(RedirectToAction("", "Home"));
     }
 }
예제 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (SecurityContext.IsAuthenticated && User.ID != SecurityContext.CurrentAccount.ID)
            {
                Response.Redirect(GetRefererURL(), true);
                return;
            }
            if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppAuthSettings.Enable)
            {
                Response.Redirect(GetRefererURL(), true);
                return;
            }
            if (!Activation && !TfaAppUserSettings.EnableForUser(User.ID))
            {
                Response.Redirect(GetRefererURL(), true);
                return;
            }

            var authCommunications = (AuthCommunications)LoadControl(AuthCommunications.Location);

            authCommunications.DisableJoin = true;
            _communitations.Controls.Add(authCommunications);

            AjaxPro.Utility.RegisterTypeForAjax(GetType());

            Page.RegisterBodyScripts("~/UserControls/Management/TfaControls/js/confirmtfa.js")
            .RegisterStyle("~/UserControls/Management/TfaControls/css/confirmtfa.less");

            if (Activation)
            {
                SetupCode = User.GenerateSetupCode(300);
            }
        }
        public static SetupCode GenerateCode(string issureId, string userAccountTitle, string userAccountSecreteKey,
                                             int qrCodeWidth, int qrCodeHeight)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            SetupCode setupInfo        = tfa.GenerateSetupCode(issureId, userAccountTitle, userAccountSecreteKey, qrCodeWidth, qrCodeHeight);

            return(setupInfo);
        }
예제 #5
0
        private void frmAccountIssuer_Load(object sender, EventArgs e)
        {
            accountCode = Membership.GeneratePassword(16, 6);

            var tfa = new TwoFactorAuthenticator();

            info = tfa.GenerateSetupCode("CAESAR", accountCode, 300, 300);
        }
예제 #6
0
        /// <summary>
        /// Provide information for setting up google authenticator, if the user is new.
        /// </summary>
        /// <returns>String representing the manual setup key users must enter into google authenticator.</returns>
        public string SetUpGoogleAuthenticator()
        {
            this.tfa = new TwoFactorAuthenticator();
            SetupCode setupInfo = this.tfa.GenerateSetupCode("ExpenseTrackerPlus", this.user.Username, this.user.SecretKey, false, 3);

            this.QRCodeImageURL = Convert.FromBase64String(setupInfo.QrCodeSetupImageUrl.Substring(22));
            return(setupInfo.ManualEntryKey);
        }
예제 #7
0
        public ActionResult EnableGoogleAuthenticator()
        {
            SetupCode codigos = ObtenerCodigoRegistroGoogleAuthenticator();

            ViewBag.URLImagenQR  = codigos.QrCodeSetupImageUrl;
            ViewBag.CodigoManual = codigos.ManualEntryKey;

            return(View());
        }
예제 #8
0
        public SetupCode GenerateTFA()
        {
            TwoFactorAuthenticator tfao = new TwoFactorAuthenticator();
            string    ihex = ForumUtilities.GetRandomB64(6);
            SetupCode sc   = tfao.GenerateSetupCode("Frenetic LLC", UserName, ihex, 300, 300, true);

            Update(Builders <BsonDocument> .Update.Set(TFA_INTERNAL, ihex));
            GenerateBackups();
            return(sc);
        }
예제 #9
0
        public ActionResult SetupAuthentication()
        {
            TwoFactorAuthenticator twoFactor = new TwoFactorAuthenticator();
            SetupCode code       = twoFactor.GenerateSetupCode("TestApp", "user", "secret", 300, 300);
            string    url        = code.QrCodeSetupImageUrl;
            string    manualCode = code.ManualEntryKey;

            ViewBag.AuthMessage = "<h2>QR-Code</h2><br/><br/><img src='" + url + "'/><br/><br/><h2>Token for manual entry</h2><br/>" + manualCode;
            return(View());
        }
예제 #10
0
        /// <summary>
        /// shows the set up authentication
        /// qr code
        /// and token
        /// </summary>
        /// <returns></returns>
        public ActionResult SetupAuthentication()
        {
            //generate token and qr code
            TwoFactorAuthenticator twoFactorAuthenticator = new TwoFactorAuthenticator();
            SetupCode setupCode = twoFactorAuthenticator.GenerateSetupCode("M183", "*****@*****.**", "My_Secret_Key", 300, 300);

            //print
            ViewBag.Message = "<h2>QR-Code:</h2> <br/><br/> " +
                              "<img src='" + setupCode.QrCodeSetupImageUrl + "' /> <br/><br/> " +
                              "<h2>Token for manual entry</h2> <br/>" +
                              setupCode.ManualEntryKey;

            return(View());
        }
예제 #11
0
 public ActionResult googleAuthPage()
 {
     try {
         AzureConnection        db        = new AzureConnection();
         string                 email     = Session["email"].ToString();
         var                    user_data = db.user_table.Where(a => a.email == email).FirstOrDefault();
         TwoFactorAuthenticator tfa       = new TwoFactorAuthenticator();
         SetupCode              setupInfo = tfa.GenerateSetupCode("TRUSTBTC", Session["email"].ToString(), Session["qrkey"].ToString(), 200, 200);
         ViewData["qrUrl"] = setupInfo.QrCodeSetupImageUrl;
         ViewBag.scanned   = user_data.qrScanned;
         return(View());
     }
     catch
     {
         return(RedirectToAction("", "Home"));
     }
 }
예제 #12
0
        public Boolean GenerateTwoFactorAuthentication()
        {
            Guid   guid          = Guid.NewGuid();
            String uniqueUserKey = guid.ToString().Replace("-", string.Empty).Substring(0, 10);

            TwoFactorAuthVerifyCode.AuthCode = uniqueUserKey;

            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            SetupCode setupInfo        = tfa.GenerateSetupCode(Branding.CurrentBrand.AppName, Profile.GetUser(Page.User.Identity.Name).Email, uniqueUserKey, false, 3);

            if (setupInfo != null)
            {
                imgQR.Src   = setupInfo.QrCodeSetupImageUrl;
                lblKey.Text = setupInfo.ManualEntryKey;
                return(true);
            }
            return(false);
        }
예제 #13
0
        private void btnGenerateQR_Click(object sender, EventArgs e)
        {
            SetupCode sc = totp.GenerateSetupCode(txtIssuer.Text, txtUser.Text, txtKey.Text, 300, 300);

            //使用Google API 生成 QR
            //pictureBox1.ImageLocation = sc.QrCodeSetupImageUrl;

            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(sc.QrCodeSetupUrl, QRCodeGenerator.ECCLevel.L);
            QRCode          qrCode      = new QRCode(qrCodeData);
            Bitmap          qrCodeImage = qrCode.GetGraphic(20);

            pictureBoxQR.Image    = qrCodeImage;
            pictureBoxQR.SizeMode = PictureBoxSizeMode.Zoom;

            lblAPI.Text    = "图像API地址" + sc.QrCodeSetupImageUrl;
            lblQRAddr.Text = "令牌(二维码地址)" + sc.QrCodeSetupUrl;
        }
예제 #14
0
        public void OnGet(string key)
        {
            unid = key;
            var str  = _db.GetString(key);
            var user = JsonConvert.DeserializeObject <LoginUser>(str);
            TwoFactorAuthenticator ta = new TwoFactorAuthenticator();

            if (string.IsNullOrEmpty(user.SecretKey))
            {
                CodeData       = ta.GenerateSetupCode(user.Name);
                user.SecretKey = CodeData.SecretKey;
                _db.SetString(key, JsonConvert.SerializeObject(user));
            }
            else
            {
                CodeData = ta.GenerateSetupCode(user.Name, user.SecretKey, true);
            }
        }
        public ActionResult Login(Account account)
        {
            PlanningSysteemEntities context = new PlanningSysteemEntities();
            bool status = false;


            if (context.Account.Any(a => a.username == account.username && a.password == account.password))
            {
                status = true;
                Session["Username"] = account.username;

                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                string UserUniqueKey       = account.username + key;
                Session["UserUniqueKey"] = UserUniqueKey;
                SetupCode setupInfo = tfa.GenerateSetupCode("PlanningSysteem", account.username, UserUniqueKey, 300, 300);
                ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                ViewBag.SetupCode       = setupInfo.ManualEntryKey;
            }

            ViewBag.Status = status;
            return(View());
        }
예제 #16
0
    /// <summary>
    /// Generate a setup code for a Google Authenticator user to scan (with issuer ID).
    /// </summary>
    /// <param name="issuer">Issuer ID (the name of the system, i.e. 'MyApp')</param>
    /// <param name="accountTitleNoSpaces">Account Title (no spaces)</param>
    /// <param name="accountSecretKey">Account Secret Key</param>
    /// <param name="qrCodeWidth">QR Code Width</param>
    /// <param name="qrCodeHeight">QR Code Height</param>
    /// <param name="useHttps">Use HTTPS instead of HTTP</param>
    /// <returns>SetupCode object</returns>
    public SetupCode GenerateSetupCode(string issuer, string accountTitleNoSpaces, string accountSecretKey, int qrCodeWidth, int qrCodeHeight, bool useHttps)
    {
        if (accountTitleNoSpaces == null)
        {
            throw new NullReferenceException("Account Title is null");
        }

        accountTitleNoSpaces = accountTitleNoSpaces.Replace(" ", "");

        SetupCode sC = new SetupCode
        {
            Account          = accountTitleNoSpaces,
            AccountSecretKey = accountSecretKey
        };

        string encodedSecretKey = EncodeAccountSecretKey(accountSecretKey);

        sC.ManualEntryKey = encodedSecretKey;

        string provisionUrl = null;

        if (string.IsNullOrEmpty(issuer))
        {
            provisionUrl = UrlEncode(string.Format("otpauth://totp/{0}?secret={1}", accountTitleNoSpaces, encodedSecretKey));
        }
        else
        {
            provisionUrl = UrlEncode(string.Format("otpauth://totp/{0}?secret={1}&issuer={2}", accountTitleNoSpaces, encodedSecretKey, UrlEncode(issuer)));
        }

        string protocol = useHttps ? "https" : "http";

        sC.QrCodeSetupImageUrl = string.Format("{0}://chart.googleapis.com/chart?cht=qr&chs={1}x{2}&chl={3}", protocol, qrCodeWidth, qrCodeHeight, provisionUrl);

        return(sC);
    }
        /// <summary>
        /// return is credential provide by user is right or not
        /// </summary>
        /// <param name="model">login model class</param>
        /// <param name="roles">out roles , has role list of user</param>
        /// <param name="ctx" ></param>
        /// <returns>true if athenicated</returns>
        public static bool Login(LoginModel model, out List <KeyNamePair> roles)
        {
            // loginModel = null;
            //bool isMatch = false;
            roles = null;
            SecureEngine.Encrypt("t"); //Initialize

            //	Cannot use encrypted password
            //if ())
            //{
            //    //log.warning("Cannot use Encrypted Password");
            //    return false;
            //}
            //	Authentification
            bool    authenticated = false;
            bool    isLDAP        = false;
            MSystem system        = MSystem.Get(new Ctx());
            string  output        = "";

            if (system != null && system.IsLDAP())
            {
                authenticated = system.IsLDAP(model.Login1Model.UserValue, model.Login1Model.Password, out output);

                isLDAP = true;
            }
            //Save Failed Login Count and Password validty in cache
            GetSysConfigForlogin();


            int fCount            = Util.GetValueOfInt(cache[Common.Failed_Login_Count_Key]);
            int passwordValidUpto = Util.GetValueOfInt(cache[Common.Password_Valid_Upto_Key]);

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@username", model.Login1Model.UserValue);



            DataSet dsUserInfo = DB.ExecuteDataset("SELECT AD_User_ID, Value, Password,IsLoginUser,FailedLoginCount, IsOnlyLDAP FROM AD_User WHERE Value=@username", param);

            if (dsUserInfo != null && dsUserInfo.Tables[0].Rows.Count > 0)
            {
                // skipped Login user check for SuperUser (100)
                if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue) &&
                    !dsUserInfo.Tables[0].Rows[0]["IsLoginUser"].ToString().Equals("Y"))
                {
                    throw new Exception("NotLoginUser");
                }

                // output length will be greater than 0 if there is any error while ldap auth.
                //output check is applied to becuase after first login, when user redriect to home page, this functioexecutes again and password is null on that time.
                // so ldap reject auth , but user is actually authenticated. so to avoid error, this check is used.
                if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue) && dsUserInfo.Tables[0].Rows[0]["IsOnlyLDAP"].ToString().Equals("Y") &&
                    isLDAP && !authenticated)
                {
                    throw new Exception(output);
                }
            }
            else
            {
                throw new Exception("UserNotFound");
            }

            //if authenticated by LDAP or password is null(Means request from home page)
            if (!authenticated && model.Login1Model.Password != null)
            {
                string sqlEnc      = "SELECT isencrypted FROM ad_column WHERE ad_table_id=(SELECT ad_table_id FROM ad_table WHERE tablename='AD_User') AND columnname='Password'";
                char   isEncrypted = Convert.ToChar(DB.ExecuteScalar(sqlEnc));
                string originalpwd = model.Login1Model.Password;
                if (isEncrypted == 'Y' && model.Login1Model.Password != null)
                {
                    model.Login1Model.Password = SecureEngine.Encrypt(model.Login1Model.Password);
                }

                //  DataSet dsUserInfo = DB.ExecuteDataset("SELECT AD_User_ID, Value, Password,IsLoginUser,FailedLoginCount FROM AD_User WHERE Value=@username", param);
                if (dsUserInfo != null && dsUserInfo.Tables[0].Rows.Count > 0)
                {
                    //if username or password is not matching
                    if ((!dsUserInfo.Tables[0].Rows[0]["Value"].Equals(model.Login1Model.UserValue) ||
                         !dsUserInfo.Tables[0].Rows[0]["Password"].Equals(model.Login1Model.Password)) ||
                        (originalpwd != null && SecureEngine.IsEncrypted(originalpwd)))
                    {
                        //if current user is Not superuser, then increase failed login count
                        if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue))
                        {
                            param[0] = new SqlParameter("@username", model.Login1Model.UserValue);
                            int count = DB.ExecuteQuery("UPDATE AD_User Set FAILEDLOGINCOUNT=FAILEDLOGINCOUNT+1 WHERE Value=@username ", param);

                            if (fCount > 0 && fCount <= Util.GetValueOfInt(dsUserInfo.Tables[0].Rows[0]["FailedLoginCount"]) + 1)
                            {
                                throw new Exception("MaxFailedLoginAttempts");
                            }
                        }

                        throw new Exception("UserPwdError");
                    }
                    else// if username and password matched, then check if account is locked or not
                    {
                        if (fCount > 0 && fCount <= Util.GetValueOfInt(dsUserInfo.Tables[0].Rows[0]["FailedLoginCount"]))
                        {
                            throw new Exception("MaxFailedLoginAttempts");
                        }
                    }
                }
            }

            IDataReader dr = GetRoles(model.Login1Model.UserValue, authenticated, isLDAP);

            if (!dr.Read())             //	no record found, then return msaage that role not found.
            {
                dr.Close();
                throw new Exception("RoleNotDefined");
            }

            // if user logged in successfully, then set failed login count to 0
            DB.ExecuteQuery("UPDATE AD_User SET FailedLoginCount=0 WHERE Value=@username", param);

            int AD_User_ID = Util.GetValueOfInt(dr[0].ToString()); //User Id

            if (!cache["SuperUserVal"].Equals(model.Login1Model.UserValue))
            {
                String Token2FAKey = Util.GetValueOfString(dr["TokenKey2FA"]);
                bool   enable2FA   = Util.GetValueOfString(dr["Is2FAEnabled"]) == "Y";
                if (enable2FA)
                {
                    model.Login1Model.QRFirstTime = false;
                    TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                    SetupCode setupInfo        = null;
                    string    userSKey         = Util.GetValueOfString(dr["Value"]);
                    int       ADUserID         = Util.GetValueOfInt(dr["AD_User_ID"]);
                    // if token key don't exist for user, then create new
                    if (Token2FAKey.Trim() == "")
                    {
                        model.Login1Model.QRFirstTime = true;
                        Token2FAKey = userSKey;
                        // get Random Number
                        model.Login1Model.TokenKey2FA = GetRndNum();
                        // create Token key based on Value, UserID and Random Number
                        Token2FAKey = userSKey + ADUserID.ToString() + model.Login1Model.TokenKey2FA;
                    }
                    else
                    {
                        // Decrypt token key saved in database
                        string decKey = SecureEngine.Decrypt(Token2FAKey);
                        Token2FAKey = userSKey + ADUserID.ToString() + decKey;
                    }

                    string url = Util.GetValueOfString(HttpContext.Current.Request.Url.AbsoluteUri).Replace("VIS/Account/JsonLogin", "").Replace("https://", "").Replace("http://", "");

                    setupInfo = tfa.GenerateSetupCode("VA ", url + " " + userSKey, Token2FAKey, 150, 150);
                    model.Login1Model.QRCodeURL = setupInfo.QrCodeSetupImageUrl;
                }

                model.Login1Model.Is2FAEnabled = enable2FA;
            }


            if (!authenticated)
            {
                DateTime?pwdExpireDate = Util.GetValueOfDateTime(dr["PasswordExpireOn"]);
                if (pwdExpireDate == null || (passwordValidUpto > 0 && (DateTime.Compare(DateTime.Now, Convert.ToDateTime(pwdExpireDate)) > 0)))
                {
                    model.Login1Model.ResetPwd = true;
                    //if (SecureEngine.IsEncrypted(model.Login1Model.Password))
                    //    model.Login1Model.Password = SecureEngine.Decrypt(model.Login1Model.Password);
                }
            }

            roles = new List <KeyNamePair>(); //roles

            List <int> usersRoles = new List <int>();
            string     username   = "";

            do  //	read all roles
            {
                AD_User_ID = Util.GetValueOfInt(dr[0].ToString());
                int AD_Role_ID = Util.GetValueOfInt(dr[1].ToString());

                String      Name = dr[2].ToString();
                KeyNamePair p    = new KeyNamePair(AD_Role_ID, Name);
                username = Util.GetValueOfString(dr["username"].ToString());
                roles.Add(p);

                usersRoles.Add(AD_Role_ID);
            }while (dr.Read());

            dr.Close();
            model.Login1Model.AD_User_ID  = AD_User_ID;
            model.Login1Model.DisplayName = username;

            IDataReader drLogin = null;

            if (model.Login2Model == null)
            {
                try
                {
                    //* Change sub query into ineer join */

                    drLogin = DB.ExecuteReader(" SELECT l.AD_Role_ID," +
                                               " (SELECT r.Name FROM AD_ROLE r WHERE r.AD_Role_ID=l.AD_ROLE_ID) as RoleName," +

                                               " l.AD_Org_ID," +
                                               " (SELECT o.Name FROM AD_Org o WHERE o.AD_Org_ID=l.AD_Org_ID) as OrgName," +
                                               " l.AD_Client_ID," +
                                               " (SELECT c.Name FROM AD_Client c WHERE c.AD_Client_ID=l.AD_Client_ID) as ClientName," +
                                               " l.M_Warehouse_ID," +
                                               " (SELECT m.Name FROM M_Warehouse m WHERE m.M_Warehouse_Id = l.M_Warehouse_ID) as WarehouseName" +
                                               " FROM AD_LoginSetting l WHERE l.IsActive = 'Y' AND l.AD_User_ID=" + AD_User_ID);
                    if (drLogin.Read())
                    {
                        bool deleteRecord = false;

                        //Delete Login Setting
                        if (deleteRecord)
                        {
                            DB.ExecuteQuery("DELETE FROM AD_LoginSetting WHERE AD_User_ID = " + AD_User_ID);
                        }
                        else
                        {
                            model.Login2Model               = new Login2Model();
                            model.Login2Model.Role          = drLogin[0].ToString();
                            model.Login2Model.RoleName      = drLogin[1].ToString();
                            model.Login2Model.Org           = drLogin[2].ToString();
                            model.Login2Model.OrgName       = drLogin[3].ToString();
                            model.Login2Model.Client        = drLogin[4].ToString();
                            model.Login2Model.ClientName    = drLogin[5].ToString();
                            model.Login2Model.Warehouse     = drLogin[6].ToString();
                            model.Login2Model.WarehouseName = drLogin[7].ToString();
                            model.Login2Model.Date          = System.DateTime.Now.Date;
                        }
                    }
                    drLogin.Close();
                }
                catch
                {
                    if (drLogin != null)
                    {
                        drLogin.Close();
                    }
                }
            }
            return(true);
        }