Hari krishnan
Hari krishnan

Reputation: 2108

Recognize user already logged in C# WPF

I have created the registration and login form. Both work perfectly. But how do i recognize the user logged in as the PHP does by using SESSIONS and COOKIES. I can use static class to get data between different pages, but how can i retrieve the logged user data if he closes the application.

Is there any way for achieving this?

Thanks!

Upvotes: 0

Views: 1278

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

You should use user settings to do this, as this mechanism hides all the necessary work for creating files in the right locations, etc. from the developer. It works fine and it is made for stuff like this.

You design them in Visual Studio in the project properties on the "Settings" tab. Make sure to select the settings type correctly, as application settings are read-only.

Assume you have to settings UserName and UserPassword. Then, in your code, you could do this:

if (String.IsNullOrWhitespace(Properties.Settings.Default.UserName))
{
    // USER NEEDS TO LOG IN
    string userName;
    string password;

    if (Login(out userName, out password))
    {
        try
        {
            Properties.Settings.Default.UserName = Encrypt(userName);
            Properties.Settings.Default.Password = Encrypt(password);
            Properties.Settings.Default.Save();
        }
        catch (Exception exp)
        {
            ...
        }
    }
}
else
{
    // USER IS ALREADY LOGGED IN
}

private bool Login(out string userName, out string password) would be a method that shows a login user interface and returns true on success or false on failure.

private string Encrypt(string input) would be a method to encrypt a string.

Upvotes: 0

zmechanic
zmechanic

Reputation: 1990

I'm assuming that you want something like instant messenger applications like Skype, or cloud storage applications like DropBox, OneDrive or Mega do. They ask you to enter user name and password once, and then start automatically without asking for user's credentials again.

They achieve this by storing user name and password in encrypted format in the file they normally keep in application folder under specific user account. See the following link for details: How can I get the current user directory?

This is standard practice, as another user will not be automatically logged into your app, if they not entered their own credentials.

Make sure you encrypt the user name and password or the whole file before saving it to disk, otherwise it may become an easy target for password stealing malware.

Upvotes: 1

Related Questions