Esempio n. 1
0
 protected override async Task OnParametersSetAsync()
 {
     if (!string.IsNullOrEmpty(UserId))
     {
         UsernameText = await UserApiService.GetUserNameAsync(UserId);
     }
 }
Esempio n. 2
0
        /// <summary>
        ///  Deserialize information about the last logged in user; get information about user with such an id from server;
        ///  store user info in <c>CurrentUser</c> property
        /// </summary>
        private void DeserializeLastUser()
        {
            User userCandidate;

            try
            {
                userCandidate = Serializator.Deserialize <User>(FileFolderHelper.LastUserFilePath);
            }
            catch (Exception ex)
            {
                userCandidate = null;
                Logger.Log("Failed to Deserialize last user", ex);
            }
            if (userCandidate == null)
            {
                Logger.Log("User was not deserialized");
                return;
            }
            using (var restClient = new UserApiService())
            {
                userCandidate = restClient.GetUserByGuid(userCandidate.Guid);
            }
            if (userCandidate == null)
            {
                Logger.Log("Failed to relogin last user");
            }
            else
            {
                CurrentUser = userCandidate;
            }
        }
Esempio n. 3
0
        protected override async Task OnParametersSetAsync()
        {
            if (Group == null)
            {
                Header = string.Empty;
            }
            else if (!string.IsNullOrEmpty(Group.Name))
            {
                Header = Group.Name;
            }
            else
            {
                var members = await GroupService.SecureGetGroupMembersAsync(Group.Id);

                var maxCount = members.Length > 5 ? 5 : members.Length;
                var subset   = new GroupMember[maxCount];
                Array.Copy(members, 0, subset, 0, maxCount);
                var usernames      = new List <string>();
                var loggedInUserId = (await AuthenticationStateTask).LoggedInUserId();
                foreach (var gm in subset)
                {
                    if (gm.UserId != loggedInUserId)
                    {
                        var username = await UserApiService.GetUserNameAsync(gm.UserId);

                        usernames.Add(username);
                    }
                }
                usernames.Sort();
                Header = string.Join(", ", usernames.ToArray());
            }

            await base.OnParametersSetAsync();
        }
Esempio n. 4
0
 public LoginController(LoginApiService loginApiService, IAutoMapperBase autoMapperBase, UserApiService userApiService)
 {
     ApiUrl           = ConfigHelper.GetConfigPar <string>("ApiUrl");
     _loginApiService = loginApiService;
     _autoMapperBase  = autoMapperBase;
     _userApiService  = userApiService;
 }
        public async Task Should_create_new_user_in_aad(UserType userType)
        {
            const string EMAIL_STEM = EmailData.FAKE_EMAIL_STEM;

            var userRequest = new UserBuilder(EMAIL_STEM, 1)
                              .WithUserType(userType)
                              .ForApplication(Application.TestApi)
                              .BuildRequest();

            var newUserResponse = new NewUserResponse
            {
                OneTimePassword = "******",
                UserId          = "1234",
                Username        = userRequest.Username
            };

            UserApiClient.Setup(x => x.CreateUserAsync(It.IsAny <CreateUserRequest>())).ReturnsAsync(newUserResponse);
            UserApiClient.Setup(x => x.AddUserToGroupAsync(It.IsAny <AddUserToGroupRequest>()))
            .Returns(Task.CompletedTask);

            var userDetails = await UserApiService.CreateNewUserInAAD(userRequest.FirstName, userRequest.LastName, userRequest.ContactEmail, userRequest.IsProdUser);

            userDetails.OneTimePassword.Should().Be(newUserResponse.OneTimePassword);
            userDetails.UserId.Should().Be(newUserResponse.UserId);
            userDetails.Username.Should().Be(newUserResponse.Username);
        }
        private async void LoginWithFacebook(string id, string email, string name, string profilePicture)
        {
            UserApiRequest user = new UserApiRequest();

            user.RegisterProfileId = id;
            user.Email             = email;
            user.Name           = name;
            user.ProfilePicture = new ImageApiRequest()
            {
                Url = profilePicture
            };
            user.RegisterType = (int)ERegisterType.FACEBOOK;

            var response = await UserApiService.Login(user);

            if (ResponseValidator.Validate(response))
            {
                AppStatus.UserLogged = response;
                CheckUserLogged();
                StopLoading();
            }
            else
            {
                StopLoading();
            }
        }
        protected async Task AddAsync()
        {
            _messageStore.Clear();
            var userId = await UserApiService.GetUserIdAsync(Username);

            var loggedInUserId = (await AuthenticationStateTask).LoggedInUserId();

            if (userId == loggedInUserId)
            {
                _messageStore.Add(CurrentEditContext.Field("Username"), "Adding yourself is not allowed.");
                CurrentEditContext.NotifyValidationStateChanged();
                return;
            }

            if (string.IsNullOrEmpty(userId))
            {
                _messageStore.Add(CurrentEditContext.Field("Username"), $"{Username} not found");
                CurrentEditContext.NotifyValidationStateChanged();
                return;
            }

            if (Members.Any(m => m[0] == userId))
            {
                _messageStore.Add(CurrentEditContext.Field("Username"), $"{Username} already added.");
                CurrentEditContext.NotifyValidationStateChanged();
                return;
            }

            Members.Add(new string[] { userId, Username });
            await OnUpdateUsers.InvokeAsync(Members);
        }
        private async void BtnEditEmployee_Click(object sender, RoutedEventArgs e)
        {
            UserApiService service = new UserApiService();
            int            userid  = 0;

            try
            {
                RefreshLabels();
                if (dgShowEmployees.SelectedItem != null)
                {
                    userid = (dgShowEmployees.SelectedItem as UserVM).Id;
                }
                string req = await service.UpdateAsync(new UserUpdateVM { Id = userid, Name = txtName.Text, Email = txtEmail.Text });

                MessageBox.Show("Працівник відредагований успішно.");
                txtEmail.Text = "";
                txtName.Text  = "";
                FillDG();
                dgShowEmployees.SelectedItem = null;
            }
            catch (WebException wex)
            {
                ShowException(wex);
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Checks whether fields are valid and if not displays appropriate message
 /// </summary>
 /// <returns><c>true</c> if fields are valid, <c>false</c> otherwise</returns>
 private bool IsFormValid()
 {
     try
     {
         if (!new EmailAddressAttribute().IsValid(_email))
         {
             MessageBox.Show(String.Format(Resources.SignUp_EmailIsNotValid, _email));
             return(false);
         }
         using (var restClient = new UserApiService())
         {
             if (restClient.UserExists(Login))
             {
                 MessageBox.Show(String.Format(Resources.SignUp_UserLoginAlreadyExists, _login));
                 return(false);
             }
             if (restClient.UserExists(Email))
             {
                 MessageBox.Show(String.Format(Resources.SignUp_UserEmailAlreadyExists, _email));
                 return(false);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(String.Format(Resources.SignUp_FailedToValidateData, Environment.NewLine,
                                       ex.Message));
         return(false);
     }
     return(true);
 }
Esempio n. 10
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            Xamarin.Forms.Forms.Init(e);

            await InitNotificationsAsync();

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    AppStatus.UserLogged = UserApiService.GetUserLogged();

                    if (AppStatus.UserLogged == null)
                    {
                        rootFrame.Navigate(typeof(MainPage), e.Arguments);
                    }
                    else
                    {
                        AppShell appShell = new AppShell();

                        appShell.AppFrame.Navigate(typeof(HomePage), e.Arguments, new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());

                        Window.Current.Content = appShell;
                    }
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }

            if (DeviceTypeHelper.GetDeviceFormFactorType() == DeviceFormFactorType.Phone)
            {
                await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
            }
        }
Esempio n. 11
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            try
            {
                if (AppStatus.UserLogged == null)
                {
                    MyTrapBDConfig.Initialize();

                    AppStatus.UserLogged = UserApiService.GetUserLogged();
                }

                if (AppStatus.UserLogged != null)
                {
                    Token = AppStatus.UserLogged.Token;

                    apiClient = new GoogleApiClient.Builder(Context, this, this).AddApi(LocationServices.API).Build();

                    locRequest = new LocationRequest();

                    apiClient.Connect();

                    IsStarted = true;
                }
                else
                {
                    StopSelf();
                }
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }

            return(StartCommandResult.Sticky);
        }
Esempio n. 12
0
        public async Task Should_add_prod_judge_groups()
        {
            const string EMAIL_STEM = EmailData.FAKE_EMAIL_STEM;

            var prodJudge = new UserBuilder(EMAIL_STEM, 1)
                            .WithUserType(UserType.Judge)
                            .ForApplication(Application.TestApi)
                            .IsProdUser(true)
                            .BuildUserDto();

            var nonProdJudge = new UserBuilder(EMAIL_STEM, 2)
                               .WithUserType(UserType.Judge)
                               .ForApplication(Application.TestApi)
                               .IsProdUser(false)
                               .BuildUserDto();

            UserApiClient.Setup(x => x.AddUserToGroupAsync(It.IsAny <AddUserToGroupRequest>()))
            .Returns(Task.CompletedTask);

            var groupsForProdCount = await UserApiService.AddGroupsToUser(prodJudge, "1");

            var groupsForNonProdCount = await UserApiService.AddGroupsToUser(nonProdJudge, "2");

            groupsForProdCount.Should().BeGreaterThan(groupsForNonProdCount);
        }
Esempio n. 13
0
        private async void LoginWithFacebook(Profile profile, string email)
        {
            try
            {
                StartLoading();

                UserApiRequest user = new UserApiRequest();

                user.Name              = profile.Name.ToString();
                user.RegisterType      = (int)ERegisterType.FACEBOOK;
                user.RegisterProfileId = profile.Id.ToString();
                user.Email             = email;

                user.ProfilePicture     = new ImageApiRequest();
                user.ProfilePicture.Url = profile.GetProfilePictureUri(200, 200).ToString();

                var response = await UserApiService.Login(user);

                if (ResponseValidator.Validate(response, this))
                {
                    AppStatus.UserLogged = response;
                    CheckUserLogged();
                }
                else
                {
                    StopLoading();
                }
            }
            catch (Exception exception)
            {
                InsightsUtils.LogException(exception);
            }
        }
Esempio n. 14
0
 public CourseController(CourseApiService courseApiService, StudentApiService studentApiService, UserApiService userApiService, InstructorApiService ınstructorApiService)
 {
     ApiUrl                = ConfigHelper.GetConfigPar <string>("ApiUrl");
     _studentApiService    = studentApiService;
     _courseApiService     = courseApiService;
     _userApiService       = userApiService;
     _ınstructorApiService = ınstructorApiService;
 }
        private async void BtnFindEmployee_Click(object sender, RoutedEventArgs e)
        {
            RefreshLabels();
            UserApiService service = new UserApiService();

            users = await service.GetUserAsync(new UserVM { Email = txtEmail.Text, Name = txtName.Text });

            dgShowEmployees.ItemsSource = users;
        }
Esempio n. 16
0
        private async void UpdateUser()
        {
            var result = await UserApiService.Get();

            if (!result.Error)
            {
                AppStatus.UserLogged = result;
            }
        }
Esempio n. 17
0
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                ProfileImageUrl = await UserApiService.GetProfileImageUrl();

                StateHasChanged();
            }
        }
        public async Task Should_return_false_for_nonexistent_user_in_aad()
        {
            const string USERNAME = EmailData.NON_EXISTENT_USERNAME;

            UserApiClient.Setup(x => x.GetUserByAdUserNameAsync(USERNAME)).ThrowsAsync(NotFoundError);

            var userExists = await UserApiService.CheckUserExistsInAAD(USERNAME);

            userExists.Should().BeFalse();
        }
        public async Task Should_delete_user_in_aad()
        {
            const string USERNAME = EmailData.NON_EXISTENT_USERNAME;

            UserApiClient
            .Setup(x => x.DeleteUserAsync(It.IsAny <string>()))
            .Returns(Task.CompletedTask);

            await UserApiService.DeleteUserInAAD(USERNAME);
        }
Esempio n. 20
0
        private async void RequestProfile()
        {
            var response = await UserApiService.Get();

            if (response != null && !response.Error)
            {
                AppStatus.UserLogged = response;

                UpdateInfoProfile();
            }
        }
        public async Task Should_return_true_for_existing_user_in_aad()
        {
            const string USERNAME = EmailData.NON_EXISTENT_USERNAME;

            UserApiClient
            .Setup(x => x.GetUserByAdUserNameAsync(USERNAME)).ReturnsAsync(It.IsAny <UserProfile>());

            var userExists = await UserApiService.CheckUserExistsInAAD(USERNAME);

            userExists.Should().BeTrue();
        }
Esempio n. 22
0
        private void LoadUser()
        {
            AppStatus.UserLogged = UserApiService.GetUserLogged();

            if (AppStatus.UserLogged == null)
            {
                StartActivity(typeof(LoginActivity));
            }
            else
            {
                MyTrapDroidFunctions.OpenHome(this);
            }
        }
Esempio n. 23
0
        protected async Task HandleSubmit()
        {
            if (_user.Id == 0)
            {
                await UserApiService.Post(_user);
            }
            else
            {
                await UserApiService.Put(_user.Id, _user);
            }

            NavigationManager.NavigateTo("admin/users");
        }
Esempio n. 24
0
        public async Task Should_return_not_found_when_deleting_non_existent_aad_user()
        {
            const string CONTACT_EMAIL = EmailData.NON_EXISTENT_CONTACT_EMAIL;

            UserApiService.Setup(x => x.CheckUserExistsInAAD(CONTACT_EMAIL)).Returns(Task.FromResult(false));

            var result = await Controller.DeleteADUser(CONTACT_EMAIL);

            result.Should().NotBeNull();
            var objectResult = (NotFoundObjectResult)result;

            objectResult.StatusCode.Should().Be((int)HttpStatusCode.NotFound);
        }
Esempio n. 25
0
        /// <summary>
        /// Logins user and navigates to file editor view
        /// </summary>
        /// <param name="obj"></param>
        private async void LoginExecuteAsync(object obj)
        {
            LoaderService.Instance.ShowLoader();
            var result = await Task.Run(() =>
            {
                User currentUser;
                try
                {
                    //this code added to show loader working
                    Thread.Sleep(3000);
                    using (var restClient = new UserApiService())
                    {
                        currentUser = restClient.GetUserByLoginOrEmail(Login);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(Resources.SignIn_FailedToGetUser, Environment.NewLine,
                                                  ex.Message));
                    return(false);
                }
                if (currentUser == null)
                {
                    MessageBox.Show(Resources.SignIn_FailedToLogin);
                    return(false);
                }
                try
                {
                    if (!currentUser.CheckPassword(_password))
                    {
                        MessageBox.Show(Resources.SignIn_FailedToLogin);
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(Resources.SignIn_FailedToValidatePassword, Environment.NewLine,
                                                  ex.Message));
                    return(false);
                }
                AutoLoginService.Instance.CurrentUser = currentUser;
                return(true);
            });

            LoaderService.Instance.HideLoader();
            if (result)
            {
                NavigationService.Instance.Navigate(Mode.TextEditor);
            }
        }
Esempio n. 26
0
        protected override async Task OnParametersSetAsync()
        {
            _editContext = new EditContext(Profile);
            _messages    = new ValidationMessageStore(_editContext);
            var loggedInUserId = (await AuthenticationStateTask).LoggedInUserId();

            if (!string.IsNullOrEmpty(loggedInUserId))
            {
                Profile.Slug = await UserApiService.GetUserNameAsync(loggedInUserId);
            }
            else
            {
                NavigationManager.NavigateTo($"/");
            }
        }
        public async Task Should_throw_error_whilst_checking_if_user_exists()
        {
            const string USERNAME = EmailData.NON_EXISTENT_USERNAME;

            UserApiClient.Setup(x => x.GetUserByAdUserNameAsync(USERNAME))
            .ThrowsAsync(InternalServerError);

            try
            {
                await UserApiService.CheckUserExistsInAAD(USERNAME);
            }
            catch (UserApiException ex)
            {
                ex.StatusCode.Should().Be(InternalServerError.StatusCode);
            }
        }
Esempio n. 28
0
        public async Task Should_return_not_found_for_non_existent_email()
        {
            const string CONTACT_EMAIL = "*****@*****.**";

            UserApiService
            .Setup(x => x.CheckUserExistsInAAD(It.IsAny <string>()))
            .ReturnsAsync(false);

            var response = await Controller.DeleteADUser(CONTACT_EMAIL);

            response.Should().NotBeNull();

            var result = (ObjectResult)response;

            result.StatusCode.Should().Be((int)HttpStatusCode.NotFound);
        }
Esempio n. 29
0
        public async Task Should_add_user_to_groups_by_user_type(UserType userType)
        {
            const string EMAIL_STEM = EmailData.FAKE_EMAIL_STEM;

            var user = new UserBuilder(EMAIL_STEM, 1)
                       .ForTestType(TestType.Automated)
                       .WithUserType(userType)
                       .BuildUserDto();

            UserApiClient.Setup(x => x.AddUserToGroupAsync(It.IsAny <AddUserToGroupRequest>()))
            .Returns(Task.CompletedTask);

            var groupsCount = await UserApiService.AddGroupsToUser(user, "1");

            groupsCount.Should().BeGreaterThan(0);
        }
Esempio n. 30
0
        private static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder().AddUserSecrets <Program>();

            _configuration = builder.Build();
            AppToken       = _configuration["AppToken"];
            UserToken      = _configuration["UserToken"];

            _adminApiService = new AdminApiService(new RequestService(AppToken));
            _userApiService  = new UserApiService(new RequestService(UserToken));

            //GetTokenInfo().Wait();
            GetEvents().Wait();
            //GetEventById().Wait();
            //GetLongToken().Wait();
        }