miguelgrinberg / flask-sock

Modern WebSocket support for Flask.
MIT License
272 stars 24 forks source link

Get token Erorr handling #82

Closed dimasmuly closed 2 months ago

dimasmuly commented 2 months ago

this my code activate.py :

from flask import abort, redirect, request, current_app
from flask_restful import Resource
from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadSignature
from src.account.models.users import Users
from core.smtp import send_email 
import logging
from dotenv import load_dotenv
import os

load_dotenv()

def decode_token(token):
    serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
    try:
        email = serializer.loads(token, salt='email-confirm-salt', max_age=3600)  # 3600 detik = 1 jam
        return email
    except SignatureExpired:
        raise SignatureExpired("The token has expired.")
    except BadSignature:
        raise BadSignature("The token is invalid.")
    except Exception as e:
        raise e

class ActivateAccountResource(Resource):
    def get(self, token):  # Pastikan parameter ini ada
        logging.debug(f"Received token: {token}")  # Tambahkan log ini
        CLIENT_URL = os.getenv("CLIENT_URL", "http://localhost:5000")  # Sesuaikan dengan konfigurasi Anda
        print("Activate endpoint called")
        print(f"Token received: {token}")

        try:
            email = decode_token(token)
            user = Users.query.filter_by(email=email).first()
            if user and not user.activated:
                user.activated = True
                user.save()
                return redirect(CLIENT_URL + '/login', code=302)
            else:
                abort(404)
        except SignatureExpired:
            error_message = "The token has expired. Please request a new one."
            return redirect(CLIENT_URL + f'/resend-activation-email?email={email}&error={error_message}', code=302)
        except BadSignature:
            abort(404)
        except Exception as e:
            logging.error(f"Error during activation: {str(e)}")
            abort(500)

this my code about urls.py :

from core.api import Api
from._internal.unit_competitors import FetchUnitCompetitors
from._internal.unit_hotels import FetchUnitHotels
from._internal.users import FetchAllUsers
from.account.viewsets import MyHotelViewsets, MyOTAResource, MyOTAsResource
from.account.viewsets.bridging import BridgingPointResource
from.account.viewsets.permissions import PermissionResource
from.auth.viewsets.activate import ActivateAccountResource
from.auth.viewsets.login import LoginResource, RefreshJWTResource
from.auth.viewsets.myaccount import MyAccountResource
from.auth.viewsets.password import (
    AuthResetPasswordResource,
    ForgotPasswordResource,
    ResetPasswordResource,
)
from.auth.viewsets.register import RegisterResource
from.auth.viewsets.verify import TokenVerifiedResource
from.competitors.viewsets.generics import CompetitorResource, CompetitorsResource
from.group.viewsets.member import MemberResource
from.index.viewsets.index import IndexViewset
from.systems.viewsets.ota_collections import OTACollectionsResource
from.tools.viewsets.hotel_search import HotelSearchResource
from.tools.viewsets.refresh_rate import RefreshRateResource
from flask_restful import Api

def init(app) -> None:
    route = Api(app, prefix="/v1.1")

    route.add_resource(IndexViewset, "/v1.1/index")
    api = Api(app, prefix="/v1.1")

    # Account & User Preference
    api.add_resource(
        BridgingPointResource,
        "/account/bridging-status",
        endpoint="[Account] Bridging Status",
    )
    api.add_resource(
        MyHotelViewsets, "/account/preference/hotel", endpoint="[Account] My Hotel"
    )
    api.add_resource(
        MyOTAsResource,
        "/account/preference/ota",
        endpoint="[Account] My OTAs",
    )
    api.add_resource(
        MyOTAResource,
        "/account/preference/ota/<string:ota_id>",
        endpoint="[Account] My OTAs Retrieve",
    )
    api.add_resource(
        PermissionResource,
        "/account/permissions",
        endpoint="[Account] Current Permissions",
    )

    # auth routes
    api.add_resource(ActivateAccountResource, '/auth/activate-account/<string:token>', methods=['GET'])
    api.add_resource(LoginResource, "/auth/login", endpoint="[Auth] Login")
    api.add_resource(
        RefreshJWTResource, "/auth/refresh-token", endpoint="[Auth] Refresh JWT"
    )
    api.add_resource(MyAccountResource, "/auth/myaccount", endpoint="[Auth] My Account")
    api.add_resource(RegisterResource, "/auth/register", endpoint="[Auth] Register")
    api.add_resource(
        ForgotPasswordResource,
        "/auth/forgot-password",
        endpoint="[Auth] Forgot Password",
    )
    api.add_resource(
        ResetPasswordResource,
        "/auth/reset-password",
        endpoint="[Auth] Reset Forgot Password",
    )
    api.add_resource(
        AuthResetPasswordResource,
        "/auth/account/reset-password",
        endpoint="[Auth] Reset Password",
    )
    api.add_resource(
        TokenVerifiedResource, "/auth/verify", endpoint="[Auth] Token Verification"
    )

    # competitors
    api.add_resource(
        CompetitorResource,
        "/competitors/<string:competitor_id>",
        endpoint="[Competitor] Generics Competitor Resources with :_id",
    )
    api.add_resource(
        CompetitorsResource,
        "/competitors",
        endpoint="[Competitor] Generics Competitor Resources",
    )

    # member
    api.add_resource(
        MemberResource,
        "/members",
        endpoint="[Member] Members"
    )

    # internal
    api.add_resource(
        FetchAllUsers, "/internal/users", endpoint="[Internal] Fetch all unit users"
    )
    api.add_resource(
        FetchUnitCompetitors,
        "/internal/unit-competitors",
        endpoint="[Internal] Fetch all unit competitors",
    )
    api.add_resource(
        FetchUnitHotels,
        "/internal/unit-hotels",
        endpoint="[Internal] Fetch Unit Hotels",
    )

    # systems endpoint handler
    api.add_resource(
        OTACollectionsResource, "/systems/otas", endpoint="List OTA Collections"
    )

    # tools
    api.add_resource(
        HotelSearchResource, "/tools/hotels", endpoint="Dynamic searching hotel markets"
    )
    api.add_resource(
        RefreshRateResource,
        "/tools/refresh-rate",
        endpoint="Refresh current room price",
    )

and this my error:

File "/Users/dimasmulya/Desktop/flask-backend/venv/lib/python3.10/site-packages/flask_restful/__init__.py", line 582, in dispatch_request
    resp = meth(*args, **kwargs)
TypeError: ActivateAccountResource.get() got an unexpected keyword argument 'token'
miguelgrinberg commented 2 months ago

I'm sorry but this is the wrong place to ask this question. This is the issues board for Flask-Sock, which you are not using. Try asking on Stack Overflow.