-
Notifications
You must be signed in to change notification settings - Fork 77
sms service migration to gupshup. #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
paahaad
wants to merge
3
commits into
code100x:main
Choose a base branch
from
paahaad:migrate/gupshup
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,3 +36,4 @@ yarn-error.log* | |
| # Misc | ||
| .DS_Store | ||
| *.pem | ||
| Notes | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| pub mod sms_service; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| use chrono::{Duration, TimeZone, Utc}; | ||
| use poem::web::Data; | ||
| use poem_openapi::payload; | ||
| use sha2::{Digest, Sha256}; | ||
| use std::{ | ||
| env, | ||
| time::{SystemTime, UNIX_EPOCH}, | ||
| }; | ||
|
|
||
| use crate::{error::AppError, AppState}; | ||
| use sqlx::Error; | ||
|
|
||
| const TIME_STEP: u64 = 30; // 30 seconds | ||
| pub struct SmsService { | ||
| client: reqwest::Client, | ||
| gupshup_url: String, | ||
| gupshup_uid: String, | ||
| gupshup_pass: String, | ||
| template_id: String, | ||
| } | ||
|
|
||
| impl Default for SmsService { | ||
| fn default() -> Self { | ||
| Self { | ||
| client: reqwest::Client::new(), | ||
| gupshup_url: env::var("GUPSHUP_URL").unwrap(), | ||
| gupshup_uid: env::var("GUPSHUP_UID").unwrap(), | ||
| gupshup_pass: env::var("GUPSHUP_PASS").unwrap(), | ||
| template_id: env::var("TEMPLATE_ID").unwrap(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl SmsService { | ||
| pub async fn send_otp( | ||
| &self, | ||
| state: Data<&AppState>, | ||
| number: String, | ||
| _otp: String, | ||
| ) -> Result<(), AppError> { | ||
| if !self.can_send_otp(&state, &number).await? { | ||
| return Err(AppError::RateLimitted(payload::Json( | ||
| crate::error::ErrorBody { | ||
| message: "Too Many Requests".to_string(), | ||
| }, | ||
| ))); | ||
| } | ||
|
|
||
| // update db count :TODO: Make sure to move this line below before push | ||
| let _ = state.db.update_otpc_by_number(&number).await?; | ||
|
|
||
| let _ = self.client.post(&self.gupshup_url).body("").send().await?; | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| pub async fn can_send_otp(&self, state: &Data<&AppState>, number: &str) -> Result<bool, Error> { | ||
| let user = state.db.get_user_by_number(&number).await?; | ||
| let updated_at_utc = Utc.from_utc_datetime(&user.updated_at); | ||
| if user.otp_request_count > 4 | ||
| && Utc::now().signed_duration_since(updated_at_utc) < Duration::minutes(30) | ||
| { | ||
| return Ok(false); | ||
| } | ||
| Ok(true) | ||
| } | ||
|
|
||
| pub async fn generate_otp(&self, key: &str, salt: &str) -> String { | ||
| let timestamp = SystemTime::now() | ||
| .duration_since(UNIX_EPOCH) | ||
| .unwrap() | ||
| .as_secs(); | ||
| let counter = timestamp / TIME_STEP; | ||
|
|
||
| let input = format!("{}{}{}", key, salt, counter); | ||
| let mut hasher = Sha256::new(); | ||
| hasher.update(input.as_bytes()); | ||
| let result = hasher.finalize(); | ||
|
|
||
| let offset = (result[result.len() - 1] & 0xf) as usize; | ||
| let code = ((result[offset] & 0x7f) as u32) << 24 | ||
| | (result[offset + 1] as u32) << 16 | ||
| | (result[offset + 2] as u32) << 8 | ||
| | (result[offset + 3] as u32); | ||
|
|
||
| format!("{:0>6}", code % 1_000_000) // Always returns 6 digits | ||
| } | ||
|
|
||
| pub async fn verify_otp(&self, key: &str, salt: &str, token: &str) -> bool { | ||
| if token.len() != 6 { | ||
| return false; | ||
| } | ||
| let current = self.generate_otp(key, salt).await; | ||
| token == current | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| pub enum OtpError { | ||
| RequestErr(reqwest::Error), | ||
| ResponseErr(u16), | ||
| } | ||
File renamed without changes.
3 changes: 3 additions & 0 deletions
3
latent-backend/db/migrations/002_20250201_opt_ratelimiter.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| ALTER TABLE users | ||
| ADD COLUMN otp_request_count INT DEFAULT 0, | ||
| ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we can remove this comment 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ahh' that was reminder to myself I forget to remove that. Ill do that in final PR.
actually code should be this:
let _ = self.client.post(&self.gupshup_url).body("").send().await?;
let _ = state.db.update_otpc_by_number(&number).await?;
first send the otp. if otp send success then update the count.