Approach 1: This method uses an integer account_num
to look up a user in a hashmap. It then iterates over the list of users associated with that account number to verify the entered password. It returns the address of the user object if login is successful. The major problem is that it attempts to return the address of a local variable, which can lead to undefined behavior. Moreover, there’s no clear feedback if the account_num
doesn’t exist in the hashmap.
User* login()
{
bool correct_id= false;
User* user= nullptr;
while (correct_id == false)
{
cout<<"Enter email"<<endl;
int account_num;
cin>> account_num;
cout<<"Enter password"<<endl;
string password;
cin>> password;
if (this->hashmap.find(account_num)!=this->hashmap.end())
{
for(User user_node: hashmap[account_num])
{
if(account_num==user_node.account_num && password==user_node.password)
{
cout<<"Login successful, loading menu";
user= &user_node;
correct_id = true;
}
}
return user;
}
}
}
Approach 2: This method uses the user’s email
as a key to access the hashmap directly. It then checks if the entered password matches the stored one for that email. If the login is successful, it returns the address of the user object in the hashmap. It provides clear feedback if the email doesn’t exist or the password is incorrect.
User* Login()
{
bool correct_id = false;
User* user = nullptr;
while(!correct_id)
{
string email,password;
cout<<"Enter Your Email"<<endl;
cin>>email;
cout<<"Enter Your Password"<<endl;
cin>>password;
if(this->hashmap.find(email)!=this->hashmap.end())
{
User* user_ptr= this->hashmap[email];
if(user_ptr->password==password)
{
cout<<"Login Successful,Loading Menu";
user = user_ptr;
correct_id = true;
}
else
{
cout<<"incorrect password. Try Again";
}
}
else
{
cout<<"Email Not Found. Try Again";
}
}
return user;
}
I just want to know which approach is better practice..
>Solution :
The second approach for a user login function in C++ uses a user’s email as a unique identifier. It provides direct access to user data stored in an unordered map (hashmap) using the email as a key. This approach is efficient due to the O(1) access time complexity of hashmaps.
Upon incorrect email or password entry, the user is informed and asked to try again, providing a better user experience. When login is successful, it returns a pointer to the user object, ensuring correct memory management by referencing an existing object in the hashmap, not a temporary or local one.
While this approach handles passwords in plain text, which is not secure, it provides a clear pathway for security enhancement by hashing passwords. Overall, it’s a more conventional, efficient, and user-friendly approach compared to the first one. It aligns closely with common industry practices for user authentication systems and avoids potential memory management issues.