Issue on date Handling || Time travel Bugs || Middleware || Better Approach

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:

  1. Make the deafult app timezone is UTC
  2. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật