Python Rest API user registration bassed on FastAPI framework

I’m wrote an API for dating service. This is part related to user authentification, authorization, login and etc.
FastAPI, in turn, is based on starlette web server.
You may wonder what is fastapi.Depends... -It’s interanly calling a passed function when endpoint is requested to satisfy shes dependencies. I’m don’t know what is a problem to satisfy a dependencies manually, but just using it.

Here is my code, please give me any feedback.

imports ...


app = fastapi.FastAPI(title='api', description='A very verbose API.', version='0.1')

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login", auto_error=False)  # Add GUI from to login

fastapi_http_errors = {

    'no_token_401': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
        detail="Invalid token",
        headers={"WWW-Authenticate": "Bearer"}),

    'wrong_token_403': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_403_FORBIDDEN,
        detail="Wrong email or password",  # TODO wrong token ?
        headers={"WWW-Authenticate": "Bearer"}, ),

    'not_found_404': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_404_NOT_FOUND,
        detail="Interest not found"),

    'email_already_exists_409': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_409_CONFLICT,
        detail="Email already exists"),

    'double_voting_409': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_409_CONFLICT,
        detail="Same vote for the same interest"),

    'expired_410': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_410_GONE,
        detail="Confirmation link is expired"),

    'fatal_error_503': fastapi.HTTPException(
        status_code=fastapi.status.HTTP_503_SERVICE_UNAVAILABLE,
        detail="Unknown error"),
}


@app.post("/register", status_code=201, )
def register(
        user_log_in: schemas.UserLogIn,
        db: Session = fastapi.Depends(database.get_db)):
    try:
        if not crud.read_user_by(db, column='email', value=user_log_in.email):  # If email is new
            token = services.create_access_token(email=user_log_in.email,
                                                 expires_min=config.ACCESS_TOKEN_EXPIRE_MINUTES)
            services.send_email_confirm_link(token=token, endpoint='http://127.0.0.1:8000/confirm-email')
            return crud.create_user(db=db, user=user_log_in, token=token)
        else:
            return fastapi_http_errors('email_already_exists_409')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.get("/confirm-email", status_code=303, )
def confirm_email(
        token: str = fastapi.Query(...,
                                   min_length=64, max_length=256,
                                   description="jwt_token placed in url",
                                   example='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkc2IzMjFtcEBnbWFpbC5jb20iLCJleHAiOjE2MTAzNjY1MDV9.ZT0G5bHSNBdrh-onuAp4Q6m8mqWxfjBWbIg6GLJEAgk'),
        db: Session = fastapi.Depends(database.get_db)):
    try:
        if user := services.get_user_by_token(db=db, token=token):
            if user.created_datetime + timedelta(minutes=30) > datetime.now():  # TODO change minutes to days
                crud.update_user(db=db, user=user, column='is_active', value=True)
                return fastapi.responses.RedirectResponse(url=f"http://127.0.0.1:8000/users/me?token={token}")
            else:
                return fastapi_http_errors('expired_410')
        else:
            return fastapi_http_errors('wrong_token_403')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.post("/login", response_model=schemas.Token)
def grant_token(
        form_data: OAuth2PasswordRequestForm = fastapi.Depends(),
        db: Session = fastapi.Depends(database.get_db)):
    try:
        if token := services.grant_token(db=db, email=form_data.username, password=form_data.password):
            return token
        else:
            return fastapi_http_errors('wrong_token_403')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.post("/refresh-token",
          response_model=schemas.Token)
def refresh_token(
        token: str = fastapi.Depends(oauth2_scheme),
        db: Session = fastapi.Depends(database.get_db)):
    try:
        if token:
            if user := services.get_user_by_token(db=db, token=token):
                access_token = services.create_access_token(
                    email=user.email, expires_min=config.ACCESS_TOKEN_EXPIRE_MINUTES)
                crud.update_user(db=db, user=user, column='current_token', value=access_token)
                return 'Token successfully refreshed'
            else:
                return fastapi_http_errors('wrong_token_403')
        else:
            return fastapi_http_errors('no_token_401')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.post("/logout")
def logout(token: str, db: Session = fastapi.Depends(database.get_db)):
    try:
        if token:
            if user := services.get_user_by_token(db=db, token=token):
                crud.update_user(db=db, user=user, column='current_token', value=None)  # Set token to None
                return f'Successfully logout user_id {user.id}'
            else:
                return fastapi_http_errors('wrong_token_403')
        else:
            return fastapi_http_errors('no_token_401')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.get("/users/me", status_code=200)  # response model
def read_users_me(
        token: str = fastapi.Query(None),
        jwt_token: str = fastapi.Depends(oauth2_scheme),
        db: Session = fastapi.Depends(database.get_db)):
    """
      token: url_token indeed! REST requiring '-' instead of '_' in url,
      but python variable can't contain '-', unfortunately FastAPI doesn't converting it.
    """
    try:
        if token := (jwt_token or token):
            if user := services.get_user_by_token(db=db, token=token):
                return user
            else:
                return fastapi_http_errors('wrong_token_403')
        else:
            return fastapi_http_errors('no_token_401')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.patch("/users/me", status_code=200)  # See PATCH vs PUT in module annotation.
def patch_users_me(
        column: str = fastapi.Query(..., description="Column to patch", example='email'),  # TODO restrict some columns
        value: str = fastapi.Query(..., description="New value", example='foo@gmail.com'),
        token: str = fastapi.Depends(oauth2_scheme),
        db: Session = fastapi.Depends(database.get_db)):
    try:
        if token:
            if user := services.get_user_by_token(db=db, token=token):
                crud.update_user(db=db, user=user, column=column, value=value)  # TODO test it
                return 'User successfully updated'
            else:
                return fastapi_http_errors('wrong_token_403')
        else:
            return fastapi_http_errors('no_token_401')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


@app.put("/users/me", status_code=200)  # See PATCH vs PUT in file annotation.
def put_users_me():
    pass


@app.delete("/users/me", status_code=200)  # response model
def delete_users_me(
        token: str = fastapi.Depends(oauth2_scheme),
        db: Session = fastapi.Depends(database.get_db)):
    try:
        if token := token:
            if user := services.get_user_by_token(db=db, token=token):
                crud.delete_user(db=db, user=user)
                return 'User successfully deleted'
            else:
                return fastapi_http_errors('wrong_token_403')
        else:
            return fastapi_http_errors('no_token_401')
    except Exception as e:
        raise fastapi_http_errors('fatal_error_503')


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

hooks – Creating custom post on registration in wordpress?

I am struggling to create a custom post in WordPress using register_new_user hook. The code seems to be fine but nothing happens. I have even run a debug log but there is no data regarding the code. What could I be missing?

I ahev also referenced the other post: Creating a custom post type upon registration
But still nothing works even if I select user_register hook or register_new_user hook.

The code:

add_action( ‘register_new_user’, ‘create_portfolio_post’, 10, 1 );

function create_portfolio_post( $user_id )
{
error_log(‘create_portfolio_post called with user ID: ‘ . $user_id);
// Get user info
$user_info = array();
$user_info = get_userdata( $user_id );
// $user_roles = $user_info->roles;

// New code added
// $this_user_role = implode(‘, ‘, $user_roles );
//if ($this_user_role == ‘subscriber’)
//{

// Create a new post
$user_post = array(
‘post_title’ => $user_info->nickname,
‘post_author’ => $user_id,
‘post_content’ => $user_info->nickname,
‘post_status’ => ‘publish’, // <- here is to publish
‘post_type’ => ‘portfolio’ // <- change to your cpt
);
// Insert the post into the database
wp_insert_post( $user_post );
error_log(‘wp_insert_post called with arguments: ‘);
error_log(print_r($user_post, true));
}

magento2 – How to add more new fields into already created custom module for user registration fields?

What should I do to add more fields into existing custom customer registration form?

I have already created a module for adding new fields in the user registration form and it’s working fine. For this, I have followed this link: adding new fields

But now I want to add more fields to the registration form. After adding new fields into the existing custom customer module and running the commands, no new fields show up in customers’ details in the admin panel or are found in the EAV_ATTRIBUTE table in the database. I tried updating the version of the module but nothing happens.

If I delete the module name from modules list from app/etc/config.php and from setup_module table, then the new fields are added and are shown after executing the commands. But this deletes the data of the existing old custom fields.

api – System design for license plate registration system

I need to design a license plate recognition system.

Overall setup

Summary: At a time, there will be a single vehicle, the license plate must be read with an IP camera with very low error rate, the data (license plate) should be written to a database, a web front-end/ GUI to view the saved license plates and a live feed with license plate annotations (in the UI).

Here are the following requirements:

  1. A real time api which takes a frame and returns the license plate labels.
  2. The api should be able to handle multiple (<100) clients.
  3. Read frames from IP camera over internet.
  4. Saving (registering) license plates in the database.
  5. Showing live feedback with annotations.

Now, what best practices should I follow to implement this system?

So far, my design is like below:

As, the object detection api needs to be fast, we are using a C++ api of yolov4 with C++ gRPC service.

For the other part of the system (saving database, live feedback), we are thinking about using a python gRPC client (that will be in the same machine), mongodb database, but not sure how to implement the live feedback with annotations (this needs to be almost real-time). Need suggestions to design the system with good practices.

magento2 – How to Pre filled form data in the registration form Magento 2

How to auto filled data, when I enter URL like xxx.com/customer/account/create?firstname=test it shows value test in firstname field as per the screenshot

enter image description here

Here is the path and code of first name.

/vendor/magento/module-customer/view/frontend/templates/widget/name.php

<div class="field field-name-firstname required">
            <label class="label" for="<?= $block->escapeHtmlAttr($block->getFieldId('firstname')) ?>"><span><?= $block->escapeHtml($block->getStoreLabel('firstname')) ?></span></label>
            <div class="control">
                <input type="text" id="<?= $block->escapeHtmlAttr($block->getFieldId('firstname')) ?>"
                       name="<?= $block->escapeHtmlAttr($block->getFieldName('firstname')) ?>"
                       value="<?= $block->escapeHtmlAttr($block->getObject()->getFirstname()) ?>"
                       title="<?= $block->escapeHtmlAttr($block->getStoreLabel('firstname')) ?>"
                       class="input-text <?= $block->escapeHtmlAttr($block->getAttributeValidationClass('firstname')) ?>" <?= ($block->getAttributeValidationClass('firstname') == 'required-entry') ? ' data-validate="{required:true}"' : '' ?>>
            </div>

forms – How to design an extensible, international backoffice customer registration flow

I’m looking for tips or guidelines on metaphors or UX patterns that could be helpful when (re)building a backoffice UI for registering new SME (Small/Medium Enterprise) customers and registering sales related to the same.

Challenges:

  • Our system runs in multiple separately maintained customer environments, each with a target customer group (the SMEs) that may comprise one or more countries
  • SME information is often fetchable from external sources if you have a unique identifier such as an Organization Number (and a country, since Org numbers are seldom globally unique)
  • External source availability will differ from setup to setup, and will depend on the country of the SME being registered. For some regions official registries are available, for some the cost may be prohibitive and for some there simply will not be sufficient information sources to do a proper external lookup. UX solution needs to handle that sometimes information has to be keyed in

Any tips or pointers much appreciated, as I haven’t been able to find many articles on this probably very common scenario.

Excluding Specific Fields from Profile Builder Registration Form

I understand that in order to add extra fields to the default WordPress user, one must use a plugin such as Profile Builder. Such plugins also provide short-codes for linking signup and login forms into a desired page.

The problem is – I want to add fields to the default user and NOT have them appear in the registration form. For example, I want to add an “upload your avatar” option or “about you” field to the user.. but I don’t want such fields to appear in the registration page since they are unnecessary for creating an account – the user can fill them in later – if he wants. I know I can label such fields as “not required” and the user will not be compelled to fill them in on registration – but I don’t want such fields to appear at all in the registration page – I want to keep it as concise and simple as possible.

How can one achieve that using Profile Builder? I have searched for add-ons but with no luck.

Would you recommend another profile manager plugin that handles this issue better?

NB – I have 3 main tasks at hand

  • Extend the default user profile with custom fields
  • Enable a profile management system to link up later with BuddyPress
  • Create custom Login & Registration form pages.. (with custom selected fields only)

and it seems like Profile Builder has the ability to do all of that – but the inescapable issue is that the logic between these 3 phases is interlaced and thus hinders the flexibility of design and makes the entire thing.. less modular.

I don’t mind at all using a different plugin for each of these “3 phases” as long as these plugins integrate well together and also integrate nicely with BuddyPress.

commerce – PDOException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘registration

Using: commerce+entity registration+commerce registration

During the checkout sequence, after completing the registration step, I get this fatal error:

PDOException : SQLSTATE(23000): Integrity constraint violation: 1062 Duplicate entry ‘registration-144-0-0-und’ for key ‘PRIMARY’: INSERT INTO {field_data_field_nom} (entity_type, entity_id, revision_id, bundle, delta, language, field_nom_value, field_nom_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array ( (:db_insert_placeholder_0) => registration (:db_insert_placeholder_1) => 144 (:db_insert_placeholder_2) => 144 (:db_insert_placeholder_3) => formulaire_inscription (:db_insert_placeholder_4) => 0 (:db_insert_placeholder_5) => und (:db_insert_placeholder_6) => dfgh (:db_insert_placeholder_7) => ) in field_sql_storage_field_storage_write() (line 514 in /home//public_html///modules/field/modules/field_sql_storage/field_sql_storage.module).

I have tried to disable some rules that could be problematic, to disable multilanguage (entity registration have some problem whit multilang)… nothing.

What can be the cause of this error?

Thx