Django Session counter - django

I'm making a food order project in Django, and I want to set unique order numbers for quick verification of the user when they come to pick the food up after the order.
If I create a random combination of numbers and letters, there can be an issue of two orders having the same order number. Is it possible to make the order number unique to each session?

Just use normal incremental order numbers and One Time Passwords(OTP)
User pyotp to generate random OTP for order.
When user orders, create a secret string. Then Generate an OTP for user and send it to them.
When they arrive to pick up, they show the OTP. You can check it using pyotp and the secret string to verify.
Use counter based OTP.
Store the secret key in the order model.
Simple and effective.

Are you storing this on the request.session or is it a model in the database? If it's the model in the database that's a lot simpler. Just set the unique=True kwarg in the field. Though you still have to generate the unique fields.
Look at this guy's _createHash function in his question. Combined with the accepted answer you can create unique order ID's this way. If it's just attached the the request.session object, it'll be more difficult(if not impossible) to be 100% sure that the string has not been repeated, because there's no way to query all the existing Sessions for a custom added attribute. I don't think session is the word you're looking for, though.

Related

User Friendly Unique Identifier For DynamoDB

In my DynamoDB table named users, I need a unique identifier, which is easy for users to remember.
In a RDBMS I can use auto increment id to meet the requirement.
As there is no way to have auto increment id in DynamoDB, is there a way to meet this requirement?
If I keep last used id in another table (lastIdTable) retrieve it before adding new document, increment that number and save updated numbers in both tables (lastIdTable and users), that will be very inefficient.
UPDATE
Please note that there's no way of using an existing attribute or getting users input for this purpose.
Since it seems you must create a memorable userId without any information about the user, I’d recommend that you create a random phrase of 2-4 simple words from a standard dictionary.
For example, you might generate the phrase correct horse battery staple. (I know this is a userId and not a password, but the memorability consideration still applies.)
Whether you use a random number (which has similar memorability to a sequential number) or a random phrase (which I think is much more memorable), you will need to do a conditional write with the condition that the ID does not already exist, and if it does exist, you should generate a new ID and try again.
email address seems the best choice...
Either as a partition key, or use a GUID as the partition key and have a Global Secondary Index over email address.
Or as Matthew suggested in a comment, let the users pick a user name.
Docker container naming strategy might give you some idea. https://github.com/moby/moby/blob/master/pkg/namesgenerator/names-generator.go
It will result in unique (limited) yet human friendly
Examples
awesome_einstein
nasty_weinstein
perv_epstein
A similar one: https://github.com/jjmontesl/codenamize

Regularized Dynamo Secondary Keys?

I am working with a data set that has a secondary index with a sort key that ultimately has user entered information in it. For the sake of the question, consider it a "postal address" field. This model is to permit quick queries of this data for a particular postal address.
Because it is user entered I am finding myself wanting to regularize it before using it as a key. For instance, by stripping spaces and making it a common case. My thinking being that if someone made a trivial capitalization or spacing error it wouldn't be identified as a different address.
Is this a pattern that people typically do if they are creating a key on user entered data? Are "user entered keys" considered harmful? Any obvious pitfalls?
Just make sure you get your normalization function right. Simply stripping spaces might not be a great idea. For example, Hight Railroad and High Trail Road might both normalize to hightrailroad which probably isn't what you want. Instead, you might want to replace one or more consecutive spaces with a single dash or something along those lines.
If you get the normalization right, you should be fine. Others have mentioned vulnerabilities related to overwriting data but you said that this is a Global Secondary Index. You can't write to a GSI so you don't need to worry about this. Also, the user entered data is the sort key. As long as you control the hash key, you will be fine.
One thing I would be cautious of is the data distribution. Any time there is a user-influenced key whether it be direct user input or a side effect of a user action such as a timestamp, you need to take care to avoid unbalanced data distributions which could lead to hot shards and/or throttling

What is the best way to have user specific numbering in Django?

I'm making a web site for a friend for a small business, and for each user, I want them to be able to access their orders by number which starts from 1 for each user, but in the backend this should be a global numbering. So for each user, their first order will be at /orders/1/ and so on. Is there a consensus on how this should be achieved in general? Way I see it, I can do this 2 ways:
Store the number in another column in the orders table. I'd prefer not to do this because I'm not entirely sure how to handle deletions without going through and updating all the records of the user. If someone knows the edge cases I need to handle, I might go with this.
OR
For every queryset I make when getting the orders page for each user I handle the numbering, benefit of this is that it will always give the correct numbering, especially if I just do it in the template. Right now this seems easier, but I have a feeling this would give rise to problems in the future. Main problem I see is I'm not sure how to make it link to the correct url without the primary key being in that url.
I recommend you to store MyUser in a separate app, say accounts
class MyUser(BaseUser):
# extra fields
And store Order in a separate app, say order
from accounts.models import MyUser
class Order(models.Model):
user = models.ForeignKey(MyUser)
order_num = models.IntegerField()
# other fields
keep update this order_num by the count of orders the user has made.
to get the count,
count = Order.objects.filter(user==request.user).count()

Keep track of all objects created using a form

Ok, this might take a bit of explanation.
I have a class called PurchaceOrder, which has a form with 18 fields. A lot of the time, there will be several PurchaceOrders with the first 12 fields being the same. To facilitate this (and remove the chance of a user making an error when trying to make the 12 fields the same every time) I have a form that allows the user to add more than one PurchaceOrder with the first 12 Fields being carried over from one entry to the next. This is all fine and good, and is working very well.
However; I need a splash page after the user is done adding all of his/her PurchaceOrders, that shows all the entries that were just made. This means I need to track the new entries that are being created, but I can't think of a way to do this. For now I'm just filtering the categories, so that the PurchaceOrders with the first 12 fields being the same as the ones just entered are displayed, but this obviously won't really work (there could be a previous entry that has those 12 fields that are the same). What I'd really like to have is a list of Primary Keys of the entries that were just created. I could then pass this information onto the view that's responsible for the confirmation landing page.
In my current view I have the following:
if form.is_valid():
entry=form.save()
My thinking was that I could then do something like:
pks = [pks, entry.id]
I don't know where I would instantiate the list. If I did it in the view, it would be whipped out every time the page was reloaded.
I'd appreciate any help.
My first thought would be to have a separate class/method/function that keeps track of the PurchaceOrder's in each form. The ID could be tied to the result through a database or array/linked list that is auto-incremented when a new PurchaceOrder is created.
As far as instantiating the list, have it instantiated when the class is first called, or have it as a separate class. After writing that, a separate class makes more sense, which is probably why I posted it that way originally.
After leaving this alone for a long time, I've finally come up with a suitable solution. What I've done is created a url conf that has a regex of (?P<match>/+)/in it. That rexeg will be used to contain an arbitrary number of primary keys separated by /. I use this to store all of the primary keys of the PurchaseOrders that have been created (that is, when I create PurchaseOrder number 15, it redirects me to /new/15, then when I create number 16, it directs me to /new/15/16/, and so on. Then when I'm ready to confirm, I'm sent to /confirm/15/16/ and I can easily access the pk's of the entries I've just created by calling pks=match.split('/'). I can then simply iterate through pks and do something for each object. I think it's an elegant solution, as long as you don't mind your user seeing the primary keys in the url.

Unique alpha-numeric string from a unique integer? (masking IDs in a game server?)

I have a multiplayer mobile game out in the wild, it's backed by a sql database. Each game gets an ID which is just an auto-increment field. I can look up a game with a url like:
http://www.example.com/gameId=123
That url is not visible to players at the moment, but I was thinking of displaying it so users can invite friends and let non-players look on in the game as they play (through a browser - at the moment everyone plays through a native app).
But the fact that I'm putting the game ID out there in the open seems like a bad idea. If someone guessed an endpoint for say deleting a game, they could do bad stuff knowing the ID (of course my endpoints are protected by user auth, but still).
Do most services mask IDs of this sort, should I send out a url like:
http://www.example.com/gameId=maskedIdAbc
and then my game server has to translate that ID into the corresponding ID in my database?
Not sure if that's overkill. If not, what's a good way to generate a unique alpha-numeric string based off a unique integer?
Thanks
Why not change the primary key of the game from an incremental ID to a GUID? The game is out in the wild but you should be able to get there in a number of steps. Add the Guid as a Field and allow games to be looked up either by ID or GUID. Update your clients to use the GUID, phase out the ID, and finally change the primary key to be the GUID.
You could hash the int, or even use the hex, but its breakable. Better to implement a complete fix, if you don't want to use a GUID you could implement your equivalent random characters that you store against each db record but why go to the trouble when GUIDs are usually Nativity supported by databases.
If range of the integers is not big, you may define tabble with unique, random alpha-num strings. I think it's the best way.
I has a similar situation and did not want to use the gameID (using your example here) in the url, as someone can use any number. I can still use the ID's, but need to add additional checking for authorizing the users.
You could use UUID to generate gameID's but I see few problems with this;
- non numeric ID will have an impact on the performance
- if this is the primary key and want to use it as FK on other tables, space
What I did;
In addition to gameID in my table, I added another column WebGameID varchar (32). After the game ID was generated, updated the WebGameID = MD5(gameID). This will be a unique 32 char string for the specific gameID. With this I was able to use gameID for internal keys and FK's ad only use WebGameID for the URL for limiting user manipulation.