コード例 #1
0
        /// <summary>
        /// Attempts to register a user
        /// </summary>
        /// <param name="parameter"> The <see cref="SecureString"/> passed in from the view for the users password </param>
        /// <returns></returns>
        public async Task RegisterAsync(object parameter)
        {
            await RunCommandAsync(() => RegisterIsRunning, async() =>
            {
                // Call the server and attempt to register with the provided credentials
                var result = await WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Register),
                    // Create API model
                    new RegisterCredentialsApiModel
                {
                    Username = Username,
                    Email    = Email,
                    Password = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Register Failed"))
                {
                    // We are done
                    return;
                }

                // Ok successfully registered (and logged in)... now get users data
                var loginResult = result.ServerResponse.ResponseGeneric;

                // Let the application view model handle what happens
                // with the successful login
                await IoC.Application.HandleSuccessfulLoginAsync(loginResult);
            });
        }
コード例 #2
0
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter"> The <see cref="SecureString"/> passed in from the view for the users password </param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Login),
                    // Create API model
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Login Failed"))
                {
                    // We are done
                    return;
                }

                // Ok successfully registered (and logged in)... now get users data
                var loginResult = result.ServerResponse.ResponseGeneric;

                // Let the application view model handle what happens
                // with the successful login
                await IoC.Application.HandleSuccessfulLoginAsync(loginResult);

                ////IMPORTANT: Never store unsecure password in variable like this
                //var pass = (parameter as IHavePassword).SecurePassword.Unsecure();
            });
        }
コード例 #3
0
        /// <summary>
        /// Updates a specific value from the client data store for the user profile details
        /// and attempts to update the server tomatch those details.
        /// for example, updating the first name of the user.
        /// </summary>
        /// <param name="displayName"> The display name for logging and display purposes of the property we are updating </param>
        /// <param name="propertyToUpdate"> The property from the <see cref="LoginCredentialsDataModel" to be updated /></param>
        /// <param name="newValue"> The new value to update the property to </param>
        /// <param name="setApiModel"> setes the correct property in the <see cref="UpdateUserProfileApiModel"/> that this property maps to </param>
        /// <returns></returns>
        private async Task <bool> UpdateUserCredentialsValueAsync(string displayName, Expression <Func <LoginCredentialsDataModel, string> > propertyToUpdate, string newValue, Action <UpdateUserProfileApiModel, string> setApiModel)
        {
            // Log it
            IoC.Logger.Log($"Saving {displayName}...", LogLevel.Debug);

            // Get the current known credentials
            var credentials = await IoC.ClientDataStore.GetLoginCredentialsAsync();

            // Get the property to update from the credentials
            var toUpdate = propertyToUpdate.GetPropertyValue(credentials);

            // Log it
            IoC.Logger.Log($"{displayName} currently {toUpdate}, updating to {newValue}", LogLevel.Debug);

            // Check if the value is the same...
            if (toUpdate == newValue)
            {
                // Log it
                IoC.Logger.Log($"{displayName} is the same, ignoring...", LogLevel.Debug);

                return(true);
            }

            // Set the property
            propertyToUpdate.SetPropertyValue(newValue, credentials);

            // Create update details
            var updateApiModel = new UpdateUserProfileApiModel();

            // Ask caller to set appropriate value
            setApiModel(updateApiModel, newValue);

            // Update the server awith the details
            var result = await WebRequests.PostAsync <ApiResponse>(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserProfile),
                // Pass the Api model
                updateApiModel,
                // Pass in user token
                bearerToken : credentials.Token);

            // If the response has an error...
            if (await result.DisplayErrorIfFailedAsync($"Update {displayName}"))
            {
                // Log it
                IoC.Logger.Log($"Failed to update {displayName}. {result.ErrorMessage}", LogLevel.Debug);

                return(false);
            }

            // Log it
            IoC.Logger.Log($"Successfully updated {displayName}. Saving to local database cache...", LogLevel.Debug);

            // Store the new user credentials to the data store
            await IoC.ClientDataStore.SaveLoginCredentialsAsync(credentials);

            // Return successful
            return(true);
        }
コード例 #4
0
        /// <summary>
        /// Saves the Password to the server
        /// </summary>
        /// <param name="self"> The details of the view model </param>
        /// <returns> Returns true if successful, false otherwise </returns>
        public async Task <bool> SavePasswordAsync()
        {
            // Lock this command to ignore any other requests while processing
            return(await RunCommandAsync(() => PasswordIsChanging, async() =>
            {
                // Log it
                IoC.Logger.Log($"Changing password...", LogLevel.Debug);

                // Get the current known credentials
                var credentials = await IoC.ClientDataStore.GetLoginCredentialsAsync();

                // Make sure the user has entered the same password
                if (Password.NewPassword.Unsecure() != Password.ConfirmPassword.Unsecure())
                {
                    // Display error
                    await IoC.UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        // TODO: Localize
                        Title = "Password mismatch",
                        Message = "New password and confirm password must match"
                    });

                    // Return fail
                    return false;
                }

                // Update the server with the new password
                var result = await WebRequests.PostAsync <ApiResponse>(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserPassword),
                    // Create API model
                    new UpdateUserPasswordApiModel
                {
                    CurrentPassword = Password.CurrentPassword.Unsecure(),
                    NewPassword = Password.NewPassword.Unsecure()
                },
                    // Pass in user token
                    bearerToken: credentials.Token);

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync($"Change Password"))
                {
                    // Log it
                    IoC.Logger.Log($"Failed to change password. {result.ErrorMessage}", LogLevel.Debug);

                    return false;
                }

                // Log it
                IoC.Logger.Log($"Successfully changed password", LogLevel.Debug);

                // Return successful
                return true;
            }));
        }
コード例 #5
0
        /// <summary>
        /// Sets the settings view model properties based on the data in the client data store
        /// </summary>
        public async Task LoadAsync()
        {
            // Update values from local cache
            await UpdateValuesFromLocalStoreAsync();

            // Get the user token
            var token = (await IoC.ClientDataStore.GetLoginCredentialsAsync()).Token;

            // If we don't have a token (so we are not logged in)...
            if (string.IsNullOrEmpty(token))
            {
                // Then do nothing
                return;
            }

            // Load user profile details from server
            var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetUserProfile),
                // Pass in user Token
                bearerToken : token);

            // If it was successful...
            if (result.Successful)
            {
                // TODO: Should we check if the values are different before saving
                await Task.Delay(2000);

                // Create data model from the response
                var dataModel = result.ServerResponse.ResponseGeneric.ToLoginCredentialsDataModel();

                // Re-add our known token
                dataModel.Token = token;

                // Store this in the client data store
                await IoC.ClientDataStore.SaveLoginCredentialsAsync(dataModel);

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync();
            }
        }