How to add multiple users in LoginFlow - Xamarin s

2020-05-06 12:21发布

问题:

I have sample xamarin forms solution. I wanted username and login functionality. I was doing some research and found nice example.

https://developer.xamarin.com/samples/xamarin-forms/Navigation/LoginFlow/

I like the way 'LoginFlow' works.

I want to hardcode the user accounts into solution and than when it comes to login user would just use their credentials which I will hard code and give them out individually.

I can see there is file called "LoginNavigation->Constants.cs". It has one user account.

My Question is how I can add multiple users in this so multiple user can login into this solution.

namespace LoginNavigation
 {
   public static class Constants
     {
        public static string Username = "Xamarin";
        public static string Password = "password";


       }
  }

Edit

Getting error when matching credentials with login form to directory.

Constants.cs

using System;
using System.Collections.Generic;

namespace LoginNavigation
{
    public class Constants
    {
        Dictionary<string, string> Credentials = new Dictionary<string, string>()
    {
        { "user1", "pass" },
        { "user2", "pass" },
        { "user3", "pass" }
    };

    }


}

On the login page; This is action when user click login.

LoginPage.cs

        async void OnLoginButtonClicked (object sender, EventArgs e)
         {
            var user = new User {
            Username = usernameEntry.Text,
            Password = passwordEntry.Text
        };

        var isValid = AreCredentialsCorrect (user);
        if (isValid) {
            App.IsUserLoggedIn = true;
            //Navigation.InsertPageBefore (new MainPageCS (), this);
            Navigation.InsertPageBefore(new MainPageCS(), Navigation.NavigationStack.First());
            await Navigation.PopAsync ();
        } else {
            messageLabel.Text = "Login failed";
            passwordEntry.Text = string.Empty;
        }
    }


    bool AreCredentialsCorrect (string user, string pass)
    {
        //return user.Username == Constants.Username && user.Password == Constants.Password;
        return (Credentials.ContainsKey(user) && Credentials[user] == pass);

    }

How I can fix above please. Thank you

回答1:

create a dictionary with all of your user/password pairs in it

Dictionary<string, string> Credentials = new Dictionary<string, string>()
    {
        { "user1", "pass" },
        { "user2", "pass" },
        { "user3", "pass" }
    };

then when you want to check them

public bool ValidateLogin(string user, string pass) 
{
  return (Credentials.ContainsKey(user) && Credentials[user] == pass);
}