I’m trying to design a simple user table with a primary key userid, and then another table that uses userid as a foreign key to the users table. Do I have the right idea here?
CREATE TABLE `users` (
`userid` INT(6) NOT NULL,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`date_join` DATE NOT NULL, <- should I just make this CURDATE instead?
`user_handle` VARCHAR(50) NOT NULL,
`date_modified` DATE NOT NULL,
PRIMARY KEY (`userid`)
)
1) How can I make userid auto increment?
2) How do you store passwords as an MD5 hash? Also, I’ve read various coders strongly recommending brcrypt, thoughts?
3) How can I set the default user_handle to be the first part of an email before the @ symbol? Such that john@smith.com would yield a user handle of john.
4) Any extra security measures I should take when designing a user database?
5) The foreign key in other tables assocated with users would need a foreign key that points to userid in users?
Thanks a lot guys, I hope that’s not too many questions!
Specify the
AUTO_INCREMENTattribute on theuseridcolumn:The main reason for recommending bcrypt over MD5 for hashing passwords is that bcrypt was designed for that purpose, whereas MD5 was designed to verify the integrity of messages: thus bcrypt is intentionally slow, whereas MD5 is intentionally fast. This means that it requires substantially more work for an attacker to brute-force bcrypt hashes versus MD5 ones.
Since both functions produce fixed-size binary output (of 16 bytes in the case of MD5 and 56 bytes in the case of bcrypt), a sensible column type is
BINARY:BINARY(16)for MD5 andBINARY(56)for bcrypt.In either case, you should be sure to salt your hashes. Salt is a random string that is concatenated with the user’s password before the (final) hash is calculated: the salt that is used is stored with the user record in the database, but is different for each user. This defeats rainbow table attacks to recover users’ passwords should your database ever become compromised.
The actual code involved in performing these actions will depend on the language, libraries and/or frameworks with which you are developing your application.
Such logic is probably most suited to your application code, but it can also be done in the SQL
INSERTstatement using MySQL’sSUBSTRING_INDEX()function:I highly recommend that you read this excellent post for a thorough explanation of related security concepts.
Yes. A foreign key exists by virtue of it being used for that purpose; if you wish to enforce foreign key constraints in MySQL (that is, ensuring that the referenced record exists in the foreign table), you will need to be using the InnoDB storage engine for both the local and foreign tables; furthermore, indexes must exist on both the local and foreign copies of the key. The constraint is then defined in the referencing table using a clause like: