Issue:
The server defaults to the African time zone, and the user receives their time in this zone, despite the existence of middleware in the PHP Laravel code.
class UpdateTimezoneMiddleware
{
/**
* Handle an incoming request.
*
* @param Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (auth()->check()) {
$user = auth()->user();
$user->update([
"timezone" => $request->header("timezone") ?? $user->timezone
]);
}
return $next($request);
}
}
Problem
My nature to make simple task just more complex.
Don’t know PHP and larval
Understanding
My understanding of source code management is as follows: the server stores the timestamp in the African timezone whenever a user is authenticated and accesses the API. Then, the timezone is updated through the request header. This way, we save data to our database with the user’s timezone, which can be utilized to display and store time.
This method is flawed
Reasoning
Here is the reason, if a person travel to the plan and register to the app whenever he travel forward time flow backend in certain condition, so even his activity is moving on in straigh line but in our database storing data in it backward time.
This is flawed an extra bug!!
Complex Nature of outshine
So, I made my new task is:
- Make the deafult app timezone is UTC
- I will not going to update the timezone rather, in response time i will change to the UTC + whatever user time zone is is.
So, In short i wanted to change the entire prodcution, staging and development handling dates mangement system to our starup. Just me a tag of 10x developer who can produce 10 times more in a given codebase.
Handling building a logic and changing a database and learning new langauge and framework at same time No thanks.
So, i decide to use the language and framework i comforatable to build that functionality is python
or fastapi
but it done by starlette
. <- using this in fastapi by the way.
class LocalTimeConversionMiddleware(BaseHTTPMiddleware):
def __convert_string_to_datetime(self, value:str):
if(type(value)!= str ):
return None
try :
return parser.parse(value)
except ValueError:
return None
async def dispatch(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
if(request.method == "GET"):
response:Response = await call_next(request)
timezone = request.headers.get("x-timezone", default="UTC")
try:
user_tz = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
user_tz = pytz.UTC
if(response.status_code == 200 and response.headers.get("content-type") == "application/json"):
response_body = b""
async for chunk in response.body_iterator:
response_body += chunk
body = response_body.decode()
print("body is " + f"{body}")
body = json.loads(body)
for key, value in body.items():
pts = self.__convert_string_to_datetime(value)
if( pts != None):
new_time_stamp = pts.astimezone(user_tz)
body[key] = new_time_stamp
print("I come here")
string_body = json.dumps(body)
response_body = string_body.encode()
headers = dict(response.headers)
print(headers)
print(headers["content-length"])
print(len(response_body))
headers["content-length"] = str(len(response_body))
return Response(content=response_body, status_code=response.status_code, headers=headers, media_type=response.media_type)
return response
return await call_next(request)
Bugs
It is incomplete because it has so many issue like string to json will give error if i use time object(Which is my main purpose to build). If json through a list then it does not handle it. Not good parsing techique just used loop.
In sort my decision was distraous for me.
But i don’t know why this simple task is giving me a nightmare. Why i have to do so many things. I was thinking it will be a common senese to use the UTC timezone timestamp ( currently directly storing to database create_at = Column(DateTime, default=datetime.datetime.now(pytz.UTC))
SqlAlchemy
) or Unix timestamp to make our treated time as the straight line, so we does not have to worry about all time travel bugs can happened. So, maybe they all use such approaches.
If have only anyone day understanding of PHP and Larval, So maybe my conclusion can flwaed maybe what i observe is wrong,
again my observation are: “the php middleware update in the database the user timezone”
Task:
Given me: In frontend geeting time of african timezone need to make again the user current timezone
Made into: A middleware which will check the get the request user the timezone data conversion and in reponse updating UTC + user_timezone
My expectation:
My exception from solution is to get the better techique to solve my task. If i am going into a right track then help in PHP larval to solve this code. If not in php larval help also accpeted in the python.
Anything which can help to reduce nightmare of mine
Source code : https://github.com/DeepeshKalura/learn-series-middleware