You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.5 KiB

  1. using API.Model;
  2. using Common.Utility;
  3. using Google.Authenticator;
  4. using System.Configuration;
  5. using System.Web;
  6. namespace API
  7. {
  8. public class GoogleAuthenticatorAPI
  9. {
  10. protected TwoFactorAuthenticator _tfa = new TwoFactorAuthenticator();
  11. protected string _key = ReadWebConfig("2FAGoogle", "");
  12. protected string _keyForEncDec = ReadWebConfig("keyForEncryptionDecryption", "");
  13. public GoogleAuthenticatorModel GenerateCodeAndImageURL(string userName)
  14. {
  15. GoogleAuthenticatorModel _model = new GoogleAuthenticatorModel();
  16. string userUniqueKeyEncrypted = EncryptDecryptUtility.Encrypt(userName + _key, _keyForEncDec);
  17. WriteSession("UserUniqueKey", userUniqueKeyEncrypted);
  18. var _googleSetupInfo = _tfa.GenerateSetupCode("JME REMIT", userName, userUniqueKeyEncrypted, 200, 200, true);
  19. _model.SetupCode = _googleSetupInfo.ManualEntryKey;
  20. _model.BarCodeImageUrl = _googleSetupInfo.QrCodeSetupImageUrl;
  21. return _model;
  22. }
  23. public GoogleAuthenticatorModel GenerateCodeAndImageURL(string userName, string userUniqueKeyEncrypted)
  24. {
  25. GoogleAuthenticatorModel _model = new GoogleAuthenticatorModel();
  26. var _googleSetupInfo = _tfa.GenerateSetupCode("JME REMIT", userName, userUniqueKeyEncrypted, 200, 200, true);
  27. _model.SetupCode = _googleSetupInfo.ManualEntryKey;
  28. _model.BarCodeImageUrl = _googleSetupInfo.QrCodeSetupImageUrl;
  29. _model.ManualEntryKey = _googleSetupInfo.ManualEntryKey;
  30. return _model;
  31. }
  32. public DbResult Verify2FA(string otp, string userUniqueKey)
  33. {
  34. DbResult _dbRes = new DbResult();
  35. if (string.IsNullOrEmpty(otp))
  36. {
  37. _dbRes.SetError("1", "OTP Code can not be blank!", null);
  38. return _dbRes;
  39. }
  40. bool isValid = _tfa.ValidateTwoFactorPIN(userUniqueKey, otp);
  41. if (isValid)
  42. _dbRes.SetError("0", "Two factor authentication verified successfully!", null);
  43. else
  44. _dbRes.SetError("1", "Please enter valid OTP!", null);
  45. return _dbRes;
  46. }
  47. public static string ReadWebConfig(string key, string defValue)
  48. {
  49. return (ConfigurationSettings.AppSettings[key] ?? defValue).ToString();
  50. }
  51. public static void WriteSession(string key, string value)
  52. {
  53. HttpContext.Current.Session[key] = value;
  54. }
  55. }
  56. }