Skip to content

Commit

Permalink
Merge pull request #3 from PSuyog97/master
Browse files Browse the repository at this point in the history
OTP Validator
  • Loading branch information
SRvSaha authored May 10, 2021
2 parents b3def72 + c412448 commit 032c361
Show file tree
Hide file tree
Showing 7 changed files with 182 additions and 20 deletions.
109 changes: 109 additions & 0 deletions CoWin.Core/Auth/OTPAuthenticator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Text;
using CoWiN.Models;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Threading;
using Newtonsoft.Json;
using CoWin.Models;
using RestSharp;
using CoWin.Providers;
using System.Net;
using System.Security.Cryptography;

namespace CoWin.Auth
{
class OTPAuthenticator
{
private IConfiguration _configuration;
public static string BEARER_TOKEN;
public OTPAuthenticator(IConfiguration configuration)
{
_configuration = configuration;
}

public void ValidateUser()
{
string endpoint = "";

if (Convert.ToBoolean(_configuration["CoWinAPI:Auth:IsToBeUsed"]))
{
endpoint = _configuration["CoWinAPI:Auth:OTPGeneratorUrl"];
}
string requestBody = JsonConvert.SerializeObject(new OtpModel
{
Mobile = _configuration["CoWinAPI:Auth:Mobile"],
Secret = _configuration["CoWinAPI:Auth:Secret"]
});
var response = GenerateOTP(endpoint, requestBody);
string otp = "";
if (response.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine($"[INFO] OTP Generated for Mobile No: {_configuration["CoWinAPI:Auth:Mobile"]} at {DateTime.Now}");
var txnID = JsonConvert.DeserializeObject<OtpModel>(response.Content);
endpoint = _configuration["CoWinAPI:Auth:OTPValidatorUrl"];
otp = ComputeSha256Hash(ReadUserInput("Please Enter OTP: "));
requestBody = JsonConvert.SerializeObject(new OtpModel
{
TransactionId = txnID.TransactionId,
Otp = otp
});
response = ValidateOTP(endpoint, requestBody);
if (response.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine($"[INFO] User Validated with Mobile No {_configuration["CoWinAPI:Auth:Mobile"]}");
BEARER_TOKEN = JsonConvert.DeserializeObject<OtpModel>(response.Content).BearerToken;
}
else
{
DisplayErrorMessage(response);
}
}
else
{
DisplayErrorMessage(response);
}

}

private IRestResponse GenerateOTP(string endpoint, string requestBody)
{
IRestResponse response = new APIFacade(_configuration).Post(endpoint, requestBody);
return response;
}

private IRestResponse ValidateOTP(string endpoint, string requestBody)
{
IRestResponse response = new APIFacade(_configuration).Post(endpoint, requestBody);
return response;
}
void DisplayErrorMessage(IRestResponse response)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[ERROR] OTP Error - ResponseCode: {response.StatusDescription} ResponseData: {response.Content}");
}
}
private string ReadUserInput(string message)
{
Console.WriteLine(message);
string userInput = Console.ReadLine();
return userInput;
}
static string ComputeSha256Hash(string rawData)
{
using (SHA256 sha256Hash = SHA256.Create())
{
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}
}
22 changes: 18 additions & 4 deletions CoWin.Core/Models/CovidVaccinationCenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ namespace CoWiN.Models
public class CovidVaccinationCenter
{
private readonly IConfiguration _configuration;

public CovidVaccinationCenter(IConfiguration configuration)
{
_configuration = configuration;
Expand All @@ -27,6 +26,12 @@ public void GetSlotsByDistrictId(string districtId, string searchDate, string va
var covidVaccinationCenters = JsonConvert.DeserializeObject<CovidVaccinationCenters>(response.Content);
GetAvailableSlots(covidVaccinationCenters);
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"[WARNING] Session Expired : Regenerating Auth Token");
new OTPAuthenticator(_configuration).ValidateUser();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Expand All @@ -43,6 +48,12 @@ public void GetSlotsByPINCode(string pinCode, string searchDate, string vaccineT
var covidVaccinationCenters = JsonConvert.DeserializeObject<CovidVaccinationCenters>(response.Content);
GetAvailableSlots(covidVaccinationCenters);
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"[WARNING] Session Expired : Regenerating Auth Token");
new OTPAuthenticator(_configuration).ValidateUser();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Expand Down Expand Up @@ -141,9 +152,6 @@ private static void DisplaySlotInfo(Center cvc, Session session)
Console.WriteLine("AvailableCapacity: " + session.AvailableCapacity);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("DateOfAvailability: " + session.Date);
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("SessionId: " + session.SessionId);
Console.ResetColor();
Console.WriteLine("Slots Available: " + string.Join(", ", session.Slots));
Console.WriteLine("***************************************************************************************************************\n");
}
Expand Down Expand Up @@ -181,6 +189,12 @@ private bool BookAvailableSlot(string sessionId, string slot, string captcha)
Console.ResetColor();
isBookingSuccessful = true;
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"[WARNING] Session Expired : Regenerating Auth Token");
new OTPAuthenticator(_configuration).ValidateUser();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Expand Down
8 changes: 7 additions & 1 deletion CoWin.Core/Models/CovidVaccinationCenterFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,26 @@ public class CovidVaccinationCenterFinder
private List<string> pinCodesToSearch = new List<string>();
private string searchDate;
private string vaccineType;

public CovidVaccinationCenterFinder()
{
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
}

public void FindSlot()
{
AuthenticateUser();
ConfigureSearchCriteria();
SearchForAvailableSlots();
}

private void AuthenticateUser()
{
new OTPAuthenticator(_configuration).ValidateUser();
}

private void SearchForAvailableSlots()
{
for (int i = 1; i < Convert.ToInt32(_configuration["CoWinAPI:TotalIterations"]); i++)
Expand Down
25 changes: 25 additions & 0 deletions CoWin.Core/Models/OTPModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace CoWin.Models
{
public partial class OtpModel
{
[JsonProperty("secret")]
public string Secret { get; set; }

[JsonProperty("mobile")]
public string Mobile { get; set; }

[JsonProperty("txnId")]
public string TransactionId { get; set; }

[JsonProperty("otp")]
public string Otp { get; set; }

[JsonProperty("token")]
public string BearerToken { get; set; }
}
}
1 change: 1 addition & 0 deletions CoWin.Core/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public class Program
{
public static void Main()
{

new CovidVaccinationCenterFinder().FindSlot();
Console.WriteLine("Press Enter to Exit");
Console.ReadKey();
Expand Down
3 changes: 2 additions & 1 deletion CoWin.Core/Providers/APIFacade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System;
using Microsoft.Extensions.Configuration;
using System.Net;
using CoWin.Auth;

namespace CoWin.Providers
{
Expand Down Expand Up @@ -34,7 +35,7 @@ private void AddGenericHeaders(IRestRequest request)
{
request.AddHeader("Origin", _configuration["CoWinAPI:SelfRegistrationPortal"]);
request.AddHeader("Referer", _configuration["CoWinAPI:SelfRegistrationPortal"]);
request.AddHeader("Authorization", $"Bearer {_configuration["CoWinAPI:ProtectedAPI:BearerToken"]}");
request.AddHeader("Authorization", $"Bearer {OTPAuthenticator.BEARER_TOKEN}");
}
}

Expand Down
34 changes: 20 additions & 14 deletions CoWin.Core/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,34 @@
"FetchCalenderByDistrictUrl": "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict",
"FetchCalenderByPINUrl": "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin"
},
"ProtectedAPI": {
"IsToBeUsed": true,
"FetchCalenderByDistrictUrl": "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByDistrict",
"FetchCalenderByPINUrl": "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByPin",
"ScheduleAppointmentUrl": "https://cdn-api.co-vin.in/api/v2/appointment/schedule",
"CaptchaGenerationUrl": "https://cdn-api.co-vin.in/api/v2/auth/getRecaptcha",
"BeneficiaryId": ""
},
"Auth": {
"IsToBeUsed": true,
"OTPGeneratorUrl": "https://cdn-api.co-vin.in/api/v2/auth/generateMobileOTP",
"OTPValidatorUrl": "https://cdn-api.co-vin.in/api/v2/auth/validateMobileOtp",
"Secret": "U2FsdGVkX18vDwDor+oOIG7vSUnINtlc/pxQcNiBulCm8LT5Sza+aIISKLqImbpMnRYgsN2QACPhggLWgZEpQg==",
"Mobile": ""
},
"MinAgeLimit": 18,
"MaxAgeLimit": 47,
"MaxAgeLimit": 45,
"MinimumVaccineAvailability": 1,
"VaccineType": "COVISHIELD",
"DoseType": 1,
"VaccineFeeType": "Free",
"SleepIntervalInMilliseconds": 2000,
"TotalIterations": 2,
"TotalIterations": 10000,
"SpoofedUserAgentToBypassWAF": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
"SelfRegistrationPortal": "https://selfregistration.cowin.gov.in",
"IsSearchToBeDoneByDistrict": false,
"IsSearchToBeDoneByPINCode": true,
"DateToSearch": "10-05-2021", // DD-MM-YYYY Format, Blank implies current date
"ProtectedAPI": {
"IsToBeUsed": true,
"FetchCalenderByDistrictUrl": "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByDistrict",
"FetchCalenderByPINUrl": "https://cdn-api.co-vin.in/api/v2/appointment/sessions/calendarByPin",
"ScheduleAppointmentUrl": "https://cdn-api.co-vin.in/api/v2/appointment/schedule",
"CaptchaGenerationUrl": "https://cdn-api.co-vin.in/api/v2/auth/getRecaptcha",
"BeneficiaryId": "",
"BearerToken": ""
}
"DateToSearch": "10-05-2021" // DD-MM-YYYY Format, Blank implies current date
},
"Districts": {
// "DistrictName": DistrictCode
Expand All @@ -36,8 +42,8 @@
"PINCodes": {
// "PlaceName": PinCode
//"Nerul": 400706,
"Nagpur": 440002
//"Bhandara": 441904
//"Nagpur": 440002
"Bhandara": 441904
//, "Andheri": 400058
//, "BKC": 400051
//, "Ghatkopar": 400077
Expand Down

0 comments on commit 032c361

Please sign in to comment.