litestar-org / litestar-fullstack

Litestar Fullstack Reference Application with React, Vite, SQLAlchemy, Docker, Task Queues, and more!
https://fullstack.litestar.dev/
MIT License
336 stars 56 forks source link

Enhancement: Production-ready validation of fields like email and password #180

Open bdoms opened 1 month ago

bdoms commented 1 month ago

Summary

I'm a big fan of Litestar, but I've been a bit lost when it comes to finding the preferred best practices for actually validating data in a strict, security minded fashion, as the main Litestar docs are sadly lacking in that regard.

Fields like emails and passwords are the most obvious examples, but here both are just str all the places I could find. No minimum lengths, no validating that an email address is an actual email address, etc.

Basic Example

Pydantic has an EmailStr type: https://docs.pydantic.dev/2.0/usage/types/string_types/#emailstr

Along with other types and features for things like URLs, stripping whitespace, forcing lowercase, etc. So I was hoping to find something similar here (regardless of whether it comes from Litestar directly vs Msgspec). Along the lines of:

class User(Struct):
    email: Annotated[EmailStr, Meta(to_lower=True)]
    password: Annotated[SecretStr, Meta(min_length=12)]

Drawbacks and Impact

I don't really see any drawbacks to doing this.

Unresolved questions

It seems like even a really solid example of how to do this on your own would be beneficial. Like a guide for the best way to do custom validation per field. But I can't find that either. Am I just missing something?

Alc-Alc commented 1 month ago

I will let @cofin comment more on this. For completion sake (you probably know this), nothing is really stopping you from using Pydantic models with its validators and data types to do what you want.

v3ss0n commented 1 month ago

I think since pydantic have all of them , we should use them. just a bit slower than msgspec tho.

bdoms commented 1 month ago

I was purposefully trying things other than Pydantic, which led me to Litestar and msgspec. I came here because even though it sounds like those tools are production ready, I can't find examples of how people are doing these things needed for production anywhere.

For what it's worth, there's already tons and tons of examples of how to do this stuff with Pydantic everywhere. We don't need anymore, IMO. What I would really appreciate though is how do you do this with Litestar and msgspec?

v3ss0n commented 1 month ago

Fair points. For msgspec https://jcristharif.com/msgspec/api.html#meta

import msgspec
from typing import Annotated

Id = Annotated[int, msgspec.Meta(gt=0)]
Email = Annotated[
    str, Meta(min_length=5, max_length=100, pattern="[^@]+@[^@]+\\.[^@]+")
]
class Comment(msgspec.Struct):
    postId: Id
    id: Id
    name: str
    email: Email
    body: str