Utils¶
The utils
module provides helper classes with static methods for common operations across the application.
datetime_utils¶
Utilities for date and time operations.
from archipy.helpers.utils.datetime_utils import DateTimeUtils
# Get current UTC time
now = DateTimeUtils.get_utc_now()
# Format datetime
formatted = DateTimeUtils.format_datetime(now, format="%Y-%m-%d %H:%M:%S")
archipy.helpers.utils.datetime_utils.DatetimeUtils
¶
A utility class for handling date and time operations, including conversions, caching, and API integrations.
This class provides methods for working with both Gregorian and Jalali (Persian) calendars, as well as utility functions for timezone-aware datetime objects, date ranges, and string formatting.
Source code in archipy/helpers/utils/datetime_utils.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
|
archipy.helpers.utils.datetime_utils.DatetimeUtils.convert_to_jalali(target_date)
staticmethod
¶
Converts a Gregorian date to a Jalali (Persian) date.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_date
|
date
|
The Gregorian date to convert. |
required |
Returns:
Type | Description |
---|---|
date
|
jdatetime.date: The corresponding Jalali date. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.is_holiday_in_iran(target_date)
classmethod
¶
Determines if the target date is a holiday in Iran.
This method leverages caching and an external API to check if the given date is a holiday.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_date
|
date
|
The date to check for holiday status. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the date is a holiday, False otherwise. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.ensure_timezone_aware(dt)
classmethod
¶
Ensures a datetime object is timezone-aware, converting it to UTC if necessary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dt
|
datetime
|
The datetime object to make timezone-aware. |
required |
Returns:
Name | Type | Description |
---|---|---|
datetime |
datetime
|
The timezone-aware datetime object. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.daterange(start_date, end_date)
classmethod
¶
Generates a range of dates from start_date to end_date, exclusive of end_date.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
start_date
|
datetime
|
The start date of the range. |
required |
end_date
|
datetime
|
The end date of the range. |
required |
Yields:
Name | Type | Description |
---|---|---|
date |
date
|
Each date in the range. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_string_datetime_from_datetime(dt, format_=None)
classmethod
¶
Converts a datetime object to a formatted string. Default format is ISO 8601.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dt
|
datetime
|
The datetime object to format. |
required |
format_
|
str | None
|
The format string. If None, uses ISO 8601. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted datetime string. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.standardize_string_datetime(date_string)
classmethod
¶
Standardizes a datetime string to the default format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
date_string
|
str
|
The datetime string to standardize. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The standardized datetime string. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_datetime_from_string_datetime(date_string, format_=None)
classmethod
¶
Parses a string to a datetime object using the given format, or ISO 8601 by default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
date_string
|
str
|
The datetime string to parse. |
required |
format_
|
str | None
|
The format string. If None, uses ISO 8601. |
None
|
Returns:
Name | Type | Description |
---|---|---|
datetime |
datetime
|
The parsed datetime object with UTC timezone. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_string_datetime_now()
classmethod
¶
Gets the current datetime as a formatted string. Default format is ISO 8601.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted datetime string. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_datetime_now()
classmethod
¶
Gets the current local datetime with timezone information.
Returns:
Name | Type | Description |
---|---|---|
datetime |
datetime
|
The current local datetime with UTC timezone. |
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_datetime_utc_now()
classmethod
¶
Gets the current UTC datetime.
Returns:
Name | Type | Description |
---|---|---|
datetime |
datetime
|
The current UTC datetime. |
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_epoch_time_now()
classmethod
¶
Gets the current time in seconds since the epoch.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The current epoch time. |
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_datetime_before_given_datetime_or_now(weeks=0, days=0, hours=0, minutes=0, seconds=0, datetime_given=None)
classmethod
¶
Subtracts time from a given datetime or the current datetime if not specified.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weeks
|
int
|
The number of weeks to subtract. |
0
|
days
|
int
|
The number of days to subtract. |
0
|
hours
|
int
|
The number of hours to subtract. |
0
|
minutes
|
int
|
The number of minutes to subtract. |
0
|
seconds
|
int
|
The number of seconds to subtract. |
0
|
datetime_given
|
datetime | None
|
The datetime to subtract from. If None, uses the current datetime. |
None
|
Returns:
Name | Type | Description |
---|---|---|
datetime |
datetime
|
The resulting datetime after subtraction. |
Source code in archipy/helpers/utils/datetime_utils.py
archipy.helpers.utils.datetime_utils.DatetimeUtils.get_datetime_after_given_datetime_or_now(weeks=0, days=0, hours=0, minutes=0, seconds=0, datetime_given=None)
classmethod
¶
Adds time to a given datetime or the current datetime if not specified.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weeks
|
int
|
The number of weeks to add. |
0
|
days
|
int
|
The number of days to add. |
0
|
hours
|
int
|
The number of hours to add. |
0
|
minutes
|
int
|
The number of minutes to add. |
0
|
seconds
|
int
|
The number of seconds to add. |
0
|
datetime_given
|
datetime | None
|
The datetime to add to. If None, uses the current datetime. |
None
|
Returns:
Name | Type | Description |
---|---|---|
datetime |
datetime
|
The resulting datetime after addition. |
Source code in archipy/helpers/utils/datetime_utils.py
options: show_root_heading: true show_source: true
file_utils¶
Utilities for file operations.
from archipy.helpers.utils.file_utils import FileUtils
# Read file content
content = FileUtils.read_file("path/to/file.txt")
# Write to file
FileUtils.write_file("path/to/output.txt", "content")
# Get file hash
file_hash = FileUtils.get_file_hash("path/to/file.txt")
# Validate file type
is_valid = FileUtils.validate_file_type("path/to/file.pdf", allowed_types=["pdf", "doc"])
archipy.helpers.utils.file_utils.FileUtils
¶
A utility class for handling file-related operations, such as creating secure links and validating file names.
Source code in archipy/helpers/utils/file_utils.py
archipy.helpers.utils.file_utils.FileUtils.create_secure_link(path, minutes=None, file_config=None)
classmethod
¶
Creates a secure link with expiration for file access.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
The file path to create a secure link for. |
required |
minutes
|
int | None
|
Number of minutes until link expiration. Defaults to the config's |
None
|
file_config
|
FileConfig | None
|
Optional file configuration object. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A secure link with a hash and expiration timestamp. |
Raises:
Type | Description |
---|---|
InvalidArgumentError
|
If the |
OutOfRangeError
|
If |
Source code in archipy/helpers/utils/file_utils.py
archipy.helpers.utils.file_utils.FileUtils.validate_file_name(file_name, file_config=None)
classmethod
¶
Validates a file name based on allowed extensions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
file_name
|
str
|
The file name to validate. |
required |
file_config
|
FileConfig | None
|
Optional file configuration object. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
|
Raises:
Type | Description |
---|---|
InvalidArgumentError
|
If |
Source code in archipy/helpers/utils/file_utils.py
options: show_root_heading: true show_source: true
jwt_utils¶
Utilities for JWT (JSON Web Token) operations.
from archipy.helpers.utils.jwt_utils import JWTUtils
# Generate JWT
token = JWTUtils.generate_jwt(
payload={"user_id": "123"},
secret="your-secret",
expires_in=3600
)
# Verify JWT
is_valid = JWTUtils.verify_jwt(token, secret="your-secret")
# Decode JWT
payload = JWTUtils.decode_jwt(token)
Utility module for JWT token operations with enhanced security and datetime handling.
This module provides a robust JWT handling implementation with support for access and refresh tokens, cryptographic security, token validation, and comprehensive error handling.
archipy.helpers.utils.jwt_utils.JWTUtils
¶
Utility class for JWT token operations with enhanced security and datetime handling.
Source code in archipy/helpers/utils/jwt_utils.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
|
archipy.helpers.utils.jwt_utils.JWTUtils.create_token(data, expires_in, additional_claims=None, auth_config=None)
classmethod
¶
Creates a JWT token with enhanced security features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
dict[str, Any]
|
Base claims data to include in the token. |
required |
expires_in
|
int
|
Token expiration time in seconds. |
required |
additional_claims
|
dict[str, Any] | None
|
Optional additional claims to include in the token. |
None
|
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The encoded JWT token. |
Raises:
Type | Description |
---|---|
ValueError
|
If data is empty or expiration is invalid |
Source code in archipy/helpers/utils/jwt_utils.py
archipy.helpers.utils.jwt_utils.JWTUtils.create_access_token(user_uuid, additional_claims=None, auth_config=None)
classmethod
¶
Creates an access token for a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_uuid
|
UUID
|
The user's UUID to include in the token. |
required |
additional_claims
|
dict[str, Any] | None
|
Optional additional claims to include in the token. |
None
|
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The encoded access token. |
Source code in archipy/helpers/utils/jwt_utils.py
archipy.helpers.utils.jwt_utils.JWTUtils.create_refresh_token(user_uuid, additional_claims=None, auth_config=None)
classmethod
¶
Creates a refresh token for a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_uuid
|
UUID
|
The user's UUID to include in the token. |
required |
additional_claims
|
dict[str, Any] | None
|
Optional additional claims to include in the token. |
None
|
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The encoded refresh token. |
Source code in archipy/helpers/utils/jwt_utils.py
archipy.helpers.utils.jwt_utils.JWTUtils.decode_token(token, verify_type=None, auth_config=None)
classmethod
¶
Decodes and verifies a JWT token with enhanced security checks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token
|
str
|
The JWT token to decode. |
required |
verify_type
|
str | None
|
Optional token type to verify (e.g., "access" or "refresh"). |
None
|
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
dict[str, Any]: The decoded token payload. |
Raises:
Type | Description |
---|---|
TokenExpiredError
|
If the token has expired. |
InvalidTokenError
|
If the token is invalid (e.g., invalid signature, audience, issuer, or type). |
Source code in archipy/helpers/utils/jwt_utils.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
|
archipy.helpers.utils.jwt_utils.JWTUtils.verify_access_token(token, auth_config=None)
classmethod
¶
Verifies an access token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token
|
str
|
The access token to verify. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
dict[str, Any]: The decoded access token payload. |
Raises:
Type | Description |
---|---|
InvalidTokenException
|
If the token is invalid or not an access token. |
TokenExpiredException
|
If the token has expired. |
Source code in archipy/helpers/utils/jwt_utils.py
archipy.helpers.utils.jwt_utils.JWTUtils.verify_refresh_token(token, auth_config=None)
classmethod
¶
Verifies a refresh token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token
|
str
|
The refresh token to verify. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
dict[str, Any]: The decoded refresh token payload. |
Raises:
Type | Description |
---|---|
InvalidTokenException
|
If the token is invalid or not a refresh token. |
TokenExpiredException
|
If the token has expired. |
Source code in archipy/helpers/utils/jwt_utils.py
archipy.helpers.utils.jwt_utils.JWTUtils.extract_user_uuid(payload)
staticmethod
¶
Extracts the user UUID from the token payload.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
payload
|
dict[str, Any]
|
The decoded token payload. |
required |
Returns:
Name | Type | Description |
---|---|---|
UUID |
UUID
|
The user's UUID. |
Raises:
Type | Description |
---|---|
InvalidTokenException
|
If the user identifier is invalid or missing. |
Source code in archipy/helpers/utils/jwt_utils.py
archipy.helpers.utils.jwt_utils.JWTUtils.get_token_expiry(token, auth_config=None)
classmethod
¶
Gets the token expiry timestamp.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token
|
str
|
The JWT token. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The token expiry timestamp in seconds. |
Raises:
Type | Description |
---|---|
InvalidTokenException
|
If the token is invalid. |
Source code in archipy/helpers/utils/jwt_utils.py
options: show_root_heading: true show_source: true
password_utils¶
Utilities for password operations.
from archipy.helpers.utils.password_utils import PasswordUtils
# Hash password
hashed = PasswordUtils.hash_password("my-password")
# Verify password
is_valid = PasswordUtils.verify_password("my-password", hashed)
# Generate secure password
password = PasswordUtils.generate_password(length=12)
# Validate password strength
is_strong = PasswordUtils.validate_password_strength("my-password")
archipy.helpers.utils.password_utils.PasswordUtils
¶
A utility class for handling password-related operations, such as hashing, verification, and validation.
Source code in archipy/helpers/utils/password_utils.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
archipy.helpers.utils.password_utils.PasswordUtils.hash_password(password, auth_config=None)
staticmethod
¶
Hashes a password using PBKDF2 with SHA256.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
password
|
str
|
The password to hash. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A base64-encoded string containing the salt and hash in the format "salt:hash". |
Source code in archipy/helpers/utils/password_utils.py
archipy.helpers.utils.password_utils.PasswordUtils.verify_password(password, stored_password, auth_config=None)
staticmethod
¶
Verifies a password against a stored hash.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
password
|
str
|
The password to verify. |
required |
stored_password
|
str
|
The stored password hash to compare against. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the password matches the stored hash, False otherwise. |
Source code in archipy/helpers/utils/password_utils.py
archipy.helpers.utils.password_utils.PasswordUtils.validate_password(password, auth_config=None, lang=LanguageType.FA)
staticmethod
¶
Validates a password against the password policy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
password
|
str
|
The password to validate. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
lang
|
LanguageType
|
The language to use for error messages. Defaults to Persian. |
FA
|
Raises:
Type | Description |
---|---|
InvalidPasswordError
|
If the password does not meet the policy requirements. |
Source code in archipy/helpers/utils/password_utils.py
archipy.helpers.utils.password_utils.PasswordUtils.generate_password(auth_config=None)
staticmethod
¶
Generates a random password that meets the policy requirements.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
A randomly generated password that meets the policy requirements. |
Source code in archipy/helpers/utils/password_utils.py
archipy.helpers.utils.password_utils.PasswordUtils.validate_password_history(new_password, password_history, auth_config=None, lang=LanguageType.FA)
classmethod
¶
Validates a new password against the password history.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
new_password
|
str
|
The new password to validate. |
required |
password_history
|
list[str]
|
A list of previous password hashes. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
lang
|
LanguageType
|
The language to use for error messages. Defaults to Persian. |
FA
|
Raises:
Type | Description |
---|---|
InvalidPasswordError
|
If the new password has been used recently or does not meet the policy requirements. |
Source code in archipy/helpers/utils/password_utils.py
options: show_root_heading: true show_source: true
string_utils¶
Utilities for string operations.
from archipy.helpers.utils.string_utils import StringUtils
# Convert to slug
slug = StringUtils.slugify("My Article Title")
# Truncate string
truncated = StringUtils.truncate("Long text here", length=10)
# Generate random string
random_str = StringUtils.generate_random_string(length=8)
# Sanitize HTML
clean_html = StringUtils.sanitize_html("<script>alert('xss')</script>")
archipy.helpers.utils.string_utils.StringUtils
¶
Bases: StringUtilsConstants
String utilities for text normalization, cleaning, and masking.
This class provides methods for handling Persian and Arabic text, including normalization, punctuation cleaning, number conversion, and masking of sensitive information like URLs, emails, and phone numbers.
Source code in archipy/helpers/utils/string_utils.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
|
archipy.helpers.utils.string_utils.StringUtils.remove_arabic_vowels(text)
classmethod
¶
Removes Arabic vowels (tashkeel) from the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing Arabic vowels. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with Arabic vowels removed. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.normalize_persian_chars(text)
classmethod
¶
Normalizes Persian characters to their standard forms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing Persian characters. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with Persian characters normalized. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.normalize_punctuation(text)
classmethod
¶
Normalizes punctuation marks in the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing punctuation marks. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with punctuation marks normalized. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.normalize_numbers(text)
classmethod
¶
Normalizes numbers in the text to English format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing numbers. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with numbers normalized to English format. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.clean_spacing(text)
classmethod
¶
Cleans up spacing issues in the text, such as non-breaking spaces and zero-width non-joiners.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text with spacing issues. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with spacing cleaned up. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.normalize_punctuation_spacing(text)
classmethod
¶
Applies proper spacing around punctuation marks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text with punctuation spacing issues. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with proper spacing around punctuation marks. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.remove_punctuation_marks(text)
classmethod
¶
Removes punctuation marks from the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing punctuation marks. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with punctuation marks removed. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.mask_urls(text, mask=None)
classmethod
¶
Masks URLs in the text with a specified mask.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing URLs. |
required |
mask
|
str | None
|
The mask to replace URLs with. Defaults to "MASK_URL". |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with URLs masked. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.mask_emails(text, mask=None)
classmethod
¶
Masks email addresses in the text with a specified mask.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing email addresses. |
required |
mask
|
str | None
|
The mask to replace emails with. Defaults to "MASK_EMAIL". |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with email addresses masked. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.mask_phones(text, mask=None)
classmethod
¶
Masks phone numbers in the text with a specified mask.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing phone numbers. |
required |
mask
|
str | None
|
The mask to replace phone numbers with. Defaults to "MASK_PHONE". |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with phone numbers masked. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.convert_english_number_to_persian(text)
classmethod
¶
Converts English numbers to Persian numbers in the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing English numbers. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with English numbers converted to Persian numbers. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.convert_numbers_to_english(text)
classmethod
¶
Converts Persian/Arabic numbers to English numbers in the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing Persian/Arabic numbers. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with Persian/Arabic numbers converted to English numbers. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.convert_add_3digit_delimiter(value)
classmethod
¶
Adds thousand separators to numbers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
int
|
The number to format. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted number with thousand separators. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.remove_emoji(text)
classmethod
¶
Removes emoji characters from the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing emojis. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with emojis removed. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.replace_currencies_with_mask(text, mask=None)
classmethod
¶
Masks currency symbols and amounts in the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing currency symbols and amounts. |
required |
mask
|
str | None
|
The mask to replace currencies with. Defaults to "MASK_CURRENCIES". |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with currency symbols and amounts masked. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.replace_numbers_with_mask(text, mask=None)
classmethod
¶
Masks numbers in the text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text containing numbers. |
required |
mask
|
str | None
|
The mask to replace numbers with. Defaults to "MASK_NUMBERS". |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text with numbers masked. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.is_string_none_or_empty(text)
classmethod
¶
Checks if a string is None
or empty (after stripping whitespace).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input string to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
|
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.normalize_persian_text(text, *, remove_vowels=True, normalize_punctuation=True, normalize_numbers=True, normalize_persian_chars=True, mask_urls=False, mask_emails=False, mask_phones=False, mask_currencies=False, mask_all_numbers=False, remove_emojis=False, url_mask=None, email_mask=None, phone_mask=None, currency_mask=None, number_mask=None, clean_spacing=True, remove_punctuation=False, normalize_punctuation_spacing=False)
classmethod
¶
Normalizes Persian text with configurable options.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text to normalize. |
required |
remove_vowels
|
bool
|
Whether to remove Arabic vowels. Defaults to |
True
|
normalize_punctuation
|
bool
|
Whether to normalize punctuation marks. Defaults to |
True
|
normalize_numbers
|
bool
|
Whether to normalize numbers to English format. Defaults to |
True
|
normalize_persian_chars
|
bool
|
Whether to normalize Persian characters. Defaults to |
True
|
mask_urls
|
bool
|
Whether to mask URLs. Defaults to |
False
|
mask_emails
|
bool
|
Whether to mask email addresses. Defaults to |
False
|
mask_phones
|
bool
|
Whether to mask phone numbers. Defaults to |
False
|
mask_currencies
|
bool
|
Whether to mask currency symbols and amounts. Defaults to |
False
|
mask_all_numbers
|
bool
|
Whether to mask all numbers. Defaults to |
False
|
remove_emojis
|
bool
|
Whether to remove emojis. Defaults to |
False
|
url_mask
|
str | None
|
The mask to replace URLs with. Defaults to |
None
|
email_mask
|
str | None
|
The mask to replace email addresses with. Defaults to |
None
|
phone_mask
|
str | None
|
The mask to replace phone numbers with. Defaults to |
None
|
currency_mask
|
str | None
|
The mask to replace currency symbols and amounts with. Defaults to |
None
|
number_mask
|
str | None
|
The mask to replace numbers with. Defaults to |
None
|
clean_spacing
|
bool
|
Whether to clean up spacing issues. Defaults to |
True
|
remove_punctuation
|
bool
|
Whether to remove punctuation marks. Defaults to |
False
|
normalize_punctuation_spacing
|
bool
|
Whether to apply proper spacing around punctuation marks. Defaults to |
False
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The normalized text. |
Source code in archipy/helpers/utils/string_utils.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
|
archipy.helpers.utils.string_utils.StringUtils.snake_to_camel_case(text)
classmethod
¶
Converts snake_case to camelCase.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text in snake_case format. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text converted to camelCase format. |
Source code in archipy/helpers/utils/string_utils.py
archipy.helpers.utils.string_utils.StringUtils.camel_to_snake_case(text)
classmethod
¶
Converts camelCase to snake_case.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The input text in camelCase format. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The text converted to snake_case format. |
Source code in archipy/helpers/utils/string_utils.py
options: show_root_heading: true show_source: true
totp_utils¶
Utilities for TOTP (Time-based One-Time Password) operations.
from archipy.helpers.utils.totp_utils import TOTPUtils
# Generate TOTP
totp_code = TOTPUtils.generate_totp(secret_key="your-secret")
# Verify TOTP
is_valid = TOTPUtils.verify_totp(totp_code, secret_key="your-secret")
# Generate secret key
secret_key = TOTPUtils.generate_secret_key()
# Get TOTP URI for QR code
totp_uri = TOTPUtils.get_totp_uri(
secret_key=secret_key,
issuer="MyApp",
account_name="user@example.com"
)
Utility module for TOTP (Time-based One-Time Password) operations.
This module provides functionality for generating and verifying TOTP codes that are commonly used for multi-factor authentication.
archipy.helpers.utils.totp_utils.TOTPUtils
¶
Utility class for TOTP (Time-based One-Time Password) operations.
This class provides methods for generating and verifying TOTP codes, as well as generating secure secret keys for TOTP initialization.
Uses the following configuration parameters from AuthConfig: - TOTP_SECRET_KEY: Master secret key for generating TOTP secrets - TOTP_HASH_ALGORITHM: Hash algorithm used for TOTP generation (default: SHA1) - TOTP_LENGTH: Number of digits in generated TOTP codes - TOTP_TIME_STEP: Time step in seconds between TOTP code changes - TOTP_EXPIRES_IN: TOTP validity period in seconds - TOTP_VERIFICATION_WINDOW: Number of time steps to check before/after - SALT_LENGTH: Length of random bytes for secure key generation
Source code in archipy/helpers/utils/totp_utils.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
|
archipy.helpers.utils.totp_utils.TOTPUtils.generate_totp(secret, auth_config=None)
classmethod
¶
Generates a TOTP code using the configured hash algorithm.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
secret
|
str | UUID
|
The secret key used to generate the TOTP code. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Type | Description |
---|---|
tuple[str, datetime]
|
A tuple containing the generated TOTP code and its expiration time. |
Raises:
Type | Description |
---|---|
InvalidArgumentError
|
If the secret is invalid or empty. |
Source code in archipy/helpers/utils/totp_utils.py
archipy.helpers.utils.totp_utils.TOTPUtils.verify_totp(secret, totp_code, auth_config=None)
classmethod
¶
Verifies a TOTP code against the provided secret.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
secret
|
str | UUID
|
The secret key used to generate the TOTP code. |
required |
totp_code
|
str
|
The TOTP code to verify. |
required |
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Type | Description |
---|---|
bool
|
|
Raises:
Type | Description |
---|---|
InvalidArgumentError
|
If the secret is invalid or empty. |
InvalidTokenError
|
If the TOTP code format is invalid. |
Source code in archipy/helpers/utils/totp_utils.py
archipy.helpers.utils.totp_utils.TOTPUtils.generate_secret_key_for_totp(auth_config=None)
staticmethod
¶
Generates a random secret key for TOTP initialization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
auth_config
|
AuthConfig | None
|
Optional auth configuration override. If not provided, uses the global config. |
None
|
Returns:
Type | Description |
---|---|
str
|
A base32-encoded secret key for TOTP initialization. |
Raises:
Type | Description |
---|---|
InvalidArgumentError
|
If the TOTP_SECRET_KEY is not configured. |
InternalError
|
If there is an error generating the secret key. |
Source code in archipy/helpers/utils/totp_utils.py
options: show_root_heading: true show_source: true
keycloak_utils¶
Utilities for Keycloak integration.
from archipy.helpers.utils.keycloak_utils import KeycloakUtils
# Get token
token = KeycloakUtils.get_keycloak_token(
username="user",
password="pass",
client_id="my-client"
)
# Validate token
is_valid = KeycloakUtils.validate_keycloak_token(token)
# Get user info
user_info = KeycloakUtils.get_keycloak_userinfo(token)
# Check role
has_role = KeycloakUtils.has_keycloak_role(token, "admin")
archipy.helpers.utils.keycloak_utils.KeycloakUtils
¶
Utility class for Keycloak authentication and authorization in FastAPI applications.
Source code in archipy/helpers/utils/keycloak_utils.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
|
archipy.helpers.utils.keycloak_utils.KeycloakUtils.fastapi_auth(resource_type_param=None, resource_type=None, required_roles=None, all_roles_required=False, required_permissions=None, admin_roles=None, lang=DEFAULT_LANG)
classmethod
¶
FastAPI decorator for Keycloak authentication and resource-based authorization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource_type_param
|
str | None
|
The parameter name in the path (e.g., 'user_uuid', 'employee_uuid') |
None
|
resource_type
|
str | None
|
The type of resource being accessed (e.g., 'users', 'employees') |
None
|
required_roles
|
frozenset[str] | None
|
Set of role names that the user must have |
None
|
all_roles_required
|
bool
|
If True, user must have all specified roles; if False, any role is sufficient |
False
|
required_permissions
|
tuple[tuple[str, str], ...] | None
|
List of (resource, scope) tuples to check |
None
|
admin_roles
|
frozenset[str] | None
|
Set of roles that grant administrative access to all resources |
None
|
lang
|
LanguageType
|
Language for error messages |
DEFAULT_LANG
|
Raises: UnauthenticatedError: If no valid Authorization header is provided InvalidTokenError: If token is invalid TokenExpiredError: If token is expired PermissionDeniedError: If user lacks required roles, permissions, or resource access InvalidArgumentError: If resource_type_param is missing when resource_type is provided
Source code in archipy/helpers/utils/keycloak_utils.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
|
archipy.helpers.utils.keycloak_utils.KeycloakUtils.async_fastapi_auth(resource_type_param=None, resource_type=None, required_roles=None, all_roles_required=False, required_permissions=None, admin_roles=None, lang=DEFAULT_LANG)
classmethod
¶
FastAPI async decorator for Keycloak authentication and resource-based authorization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resource_type_param
|
str | None
|
The parameter name in the path (e.g., 'user_uuid', 'employee_uuid') |
None
|
resource_type
|
str | None
|
The type of resource being accessed (e.g., 'users', 'employees') |
None
|
required_roles
|
frozenset[str] | None
|
Set of role names that the user must have |
None
|
all_roles_required
|
bool
|
If True, user must have all specified roles; if False, any role is sufficient |
False
|
required_permissions
|
tuple[tuple[str, str], ...] | None
|
List of (resource, scope) tuples to check |
None
|
admin_roles
|
frozenset[str] | None
|
Set of roles that grant administrative access to all resources |
None
|
lang
|
LanguageType
|
Language for error messages |
DEFAULT_LANG
|
Raises: UnauthenticatedError: If no valid Authorization header is provided InvalidTokenError: If token is invalid TokenExpiredError: If token is expired PermissionDeniedError: If user lacks required roles, permissions, or resource access InvalidArgumentError: If resource_type_param is missing when resource_type is provided
Source code in archipy/helpers/utils/keycloak_utils.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
|
options: show_root_heading: true show_source: true
Key Classes¶
DateTimeUtils¶
Class: archipy.helpers.utils.datetime_utils.DateTimeUtils
Provides datetime operations with features:
- Timezone-aware
- Microsecond precision
- Consistent across the application
JWTUtils¶
Class: archipy.helpers.utils.jwt_utils.JWTUtils
Provides JWT operations with features:
- Configurable expiration
- Custom payload support
- Multiple signing algorithms
- Token refresh capability
PasswordUtils¶
Class: archipy.helpers.utils.password_utils.PasswordUtils
Provides password operations with features:
- Secure hashing algorithm
- Salt generation
- Configurable work factor
- Protection against timing attacks