using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.BL; using Tango.BL.Builders; using Tango.BL.Entities; using Tango.Core; using Tango.Core.DI; using Tango.PPC.Common.Authentication; using Tango.PPC.Common.Navigation; namespace Tango.PPC.UI.Authentication { /// /// Represents the default PPC authentication provider. /// /// /// public class DefaultAuthenticationProvider : ExtendedObject, IAuthenticationProvider { /// /// Gets or sets the navigation manager. /// [TangoInject(TangoInjectMode.WhenAvailable)] public INavigationManager NavigationManager { get; set; } /// /// Occurs when the current logged-in user has changed. /// public event EventHandler CurrentUserChanged; private User _currentUser; /// /// Gets the current logged-in user. /// public User CurrentUser { get { return _currentUser; } private set { _currentUser = value; RaisePropertyChangedAuto(); } } /// /// Gets a value indicating whether the authentication provider is using a null user. /// public bool AuthenticationRequired { get; private set; } /// /// Performs a user login by the specified email and password. /// /// The email. /// The password. /// Determines whether to encrypt the provided password before attempting to login /// public Task Login(string email, string password, bool encrypt = true) { return Task.Factory.StartNew(() => { AuthenticationRequired = true; String hash = encrypt ? User.GetPasswordHash(password) : password; LogManager.Log($"Logging in user {email}..."); using (var db = ObservablesContext.CreateDefault()) { CurrentUser = new UserBuilder(db).Set(x => x.Email.ToLower() == email && x.Password == hash) .WithOrganization() .WithRolesAndPermissions() .Build(); } if (CurrentUser != null) { LogManager.Log($"Current user is now: {CurrentUser.Contact.FullName}."); } else { LogManager.Log("Login failed!"); } CurrentUserChanged?.Invoke(this, CurrentUser); return CurrentUser; }); } public Task Login() { return Task.Factory.StartNew(() => { AuthenticationRequired = false; CurrentUser = null; CurrentUserChanged?.Invoke(this, CurrentUser); }); } /// /// Logs-out the current logged-in user. /// public void LogOut() { LogManager.Log("Logging out current user."); CurrentUser = null; CurrentUserChanged?.Invoke(this, CurrentUser); NavigationManager.NavigateTo(NavigationView.LoginView); } } }