Beispiel #1
0
        public async void DoneClick(object sender, EventArgs e)
        {
            user.email     = emailEntry.Text;
            user.firstName = firstNameEntry.Text;
            user.lastName  = lastNameEntry.Text;
            await userRepository.AddAsync(user);

            await DisplayAlert("Profilo utente", "Profilo aggiornato correttamente", "OK");
        }
        public void AddAsync_MissingUsernameThrows()
        {
            var(repo, _) = SetupTarget();

            var user = new User {
                Username = String.Empty, Password = "******"
            };

            var ex = Assert.ThrowsAsync <MessageStoreException>(async() => await repo.AddAsync(user));

            Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCodes.Required));
        }
Beispiel #3
0
        public async Task AddAsync()
        {
            var user = new User
            {
                Id    = 2,
                Name  = "Test",
                Email = "*****@*****.**"
            };

            var userAdded = await _repository.AddAsync(user);

            Assert.True(userAdded.Id == user.Id && userAdded.Name == user.Name && userAdded.Email == user.Email);
        }
Beispiel #4
0
        public async Task Niepoprawne_dawanie_do_bazy_danych_nowego_użytkownika__Dwukrotna_próba_podania_tych_samych_danych()
        {
            // Arrange
            DbContextOptions <DataBaseContext> options = new DbContextOptionsBuilder <DataBaseContext>()
                                                         .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                                         .Options;
            DataBaseContext context        = new DataBaseContext(options);
            User            user           = new User("*****@*****.**", "tester", "secret", "user");
            UserRepository  userRepository = new UserRepository(context);
            // Act
            await userRepository.AddAsync(user);

            // Assert
            await Assert.ThrowsAsync <ArgumentException>(async() => await userRepository.AddAsync(user));
        }
Beispiel #5
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await db.FindUserByEmailAsync(model.Email);

                if (user == null)
                {
                    // добавляем пользователя в бд
                    var us = new User {
                        Email = model.Email, Password = model.Password
                    };

                    await db.AddAsync(us);

                    await Authenticate(model.Email); // аутентификация

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Некорректные логин и(или) пароль");
                }
            }
            return(View(model));
        }
        public void ValidateExistUser()
        {
            var user = new User
            {
                BirthDate = DateTime.Now.AddYears(-20),
                Cpf       = "56602275038",
                Name      = "Amilton Nobregas",
                Password  = "******"
            };
            var context    = new ContextFake().CreateContext();
            var repostorio = new UserRepository(context);

            repostorio.AddAsync(user).Wait();
            context.SaveChanges();

            var userModel = new UserModel
            {
                BirthDate = DateTime.Now.AddYears(-20),
                Cpf       = "56602275038",
                Name      = "Amilton Nobregas",
                Password  = "******",
            };

            var result = _userValidation.ValidateModel(userModel);

            Assert.False(result.Success);

            repostorio.Delete(user).Wait();
            context.SaveChanges();
        }
Beispiel #7
0
        private async Task RegisterInGame(Message message)
        {
            var fullName  = $"{message.from.first_name} {message.from.last_name}";
            var checkUser = await _userRepository.GetUserByIdAndChatIdAsync(message.from.id, message.chat.id);

            if (checkUser != null)
            {
                var foundChat = await _chatRepository.GetByTelegramId(message.chat.id);

                User user = new User()
                {
                    TelegramId = message.from.id,
                    LastName   = message.from.last_name,
                    FirstName  = message.from.first_name,
                    Chat       = foundChat
                };

                await _userRepository.AddAsync(user).ConfigureAwait(false);

                await _userRepository.SaveAsync().ConfigureAwait(false);

                string text = $"Поздравляю! Теперь {fullName} участвует в погоне за бонусами";
                _service.SendMessageAsync(message.chat.id, text);
            }
            else
            {
                string text = $"{fullName} узбагойся, дай другим отхватить кусочек бонусов!";
                _service.SendMessageAsync(message.chat.id, text);
            }
        }
Beispiel #8
0
        public async Task <UserDisplayDto> CreateUser(UserRegisterDto user)
        {
            User createdUser = new User
            {
                FirstName    = user.FirstName,
                LastName     = user.LastName,
                Email        = user.Email,
                PasswordHash = Util.HashHelper.GetMD5HashData(user.Password),
                UserName     = user.UserName,
                CreatedOn    = DateTime.Now
            };
            LMSEntities    context        = new LMSEntities();
            UserRepository userRepository = new UserRepository(context);

            createdUser = await userRepository.AddAsync(createdUser);

            UserDisplayDto displayUser = new UserDisplayDto
            {
                UserName  = user.UserName,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                Email     = user.Email,
            };

            return(displayUser);
        }
Beispiel #9
0
        public async void RegisterButton_Clicked(object sender, EventArgs e)
        {
            try
            {
                string uid = await auth.RegisterWithEmailAndPassword(emailEntry.Text, passwordEntry.Text);

                if (!string.IsNullOrEmpty(uid))
                {
                    User u = new User();
                    u.email    = emailEntry.Text;
                    u.password = passwordEntry.Text;
                    u.uid      = uid;
                    await userRepository.AddAsync(u);

                    Application.Current.MainPage = new MainPage(u);
                }
                else
                {
                    ShowError();
                }
            }catch (Exception ex)
            {
                await DisplayAlert("Errore", "L'email inserita è già utilizzata da un altro account", "OK");
            }
        }
Beispiel #10
0
        private static void GenerateOneUser(string username, string email, string password, bool isAdmin)
        {
            UserRepository userRepository = new UserRepository(connString);

            testUsernames.Add(username);

            // no need for creating the user if it already exists
            if (userRepository.FindByCondition("username", username).Result.Any())
            {
                return;
            }

            User user = new User()
            {
                Username = username,
                Email    = email,
                Password = SecurePasswordHasher.Hash(password),
                IsAdmin  = false
            };

            var addResult = userRepository.AddAsync(user);

            if (addResult.Result == null)
            {
                Console.WriteLine("A user could not be created");
            }
        }
        public async Task Should_Get_User_By_ObjectId()
        {
            IUserRepository userRepo = new UserRepository(
                _fxt.Database.GetCollection <User>("users")
                );

            // insert a new user into the collection
            string userId;
            {
                User newUser = new User
                {
                    FirstName      = "Dave",
                    DisplayId      = "dav3",
                    PassphraseHash = "passphrase~hash"
                };
                await userRepo.AddAsync(newUser);

                userId = newUser.Id;
            }

            User user = await userRepo.GetByIdAsync(userId);

            Assert.Equal("Dave", user.FirstName);
            Assert.Equal("dav3", user.DisplayId);
            Assert.Equal("passphrase~hash", user.PassphraseHash);
            Assert.True(ObjectId.TryParse(user.Id, out _), "User ID should be a Mongo ObjectID.");
            Assert.InRange(user.JoinedAt, DateTime.UtcNow.AddSeconds(-5), DateTime.UtcNow);

            Assert.Null(user.LastName);
            Assert.Null(user.Token);
            Assert.Null(user.ModifiedAt);
        }
Beispiel #12
0
        public async Task <User> FindUserByUsernameAsync(string username, bool?isAdmin = null)
        {
            var user = await _userRepository.GetUserByUsernameAsync(username.TrimStart('@'));

            if (user == null || (isAdmin.HasValue && user.IsGlobalAdmin != isAdmin))
            {
                var tlUser = await _userTL.FindUserByUsernameAsync(username);

                if (tlUser == null)
                {
                    throw new ArgumentException($"User {username} does not exists");
                }

                var existingUser = user ?? await _userRepository.GetUserByTLIdAsync(tlUser.id);

                if (existingUser != null)
                {
                    CopyUserProps(existingUser, tlUser, isAdmin);
                    await _userRepository.SaveChangesAsync();

                    user = existingUser;
                }
                else
                {
                    user = new User {
                        Id = tlUser.id
                    };
                    CopyUserProps(user, tlUser, isAdmin);
                    await _userRepository.AddAsync(user);
                }
            }

            return(user);
        }
Beispiel #13
0
        public Task HandleAsync(CreateUser command)
        {
            var user = userFactory.Create(command.FirstName, command.LastName, command.Email, command.Password, command.Role);

            command.CreatedId = user.Id;
            return(repository.AddAsync(user));
        }
Beispiel #14
0
        public async Task <ISingleResponse <UserModel> > AddUserAsync(UserModel details)
        {
            Logger.Info(CreateInvokedMethodLog(MethodBase.GetCurrentMethod().ReflectedType.FullName));
            var response = new SingleResponse <UserModel>();

            using (var transaction = DbContext.Database.BeginTransaction())
            {
                try
                {
                    var user = Mapper.Map <User>(details);

                    await UserRepository.AddAsync(user);

                    var userCredential = Mapper.Map <UserCredential>(details);
                    userCredential.User = user;
                    await UserCredentialRepository.AddAsync(userCredential);

                    transaction.Commit();
                    response.Model = Mapper.Map <UserModel>(user);
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    response.SetError(ex, Logger);
                }
            }

            return(response);
        }
Beispiel #15
0
        public async Task AddUserInformationAsync(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var userId = await userRepository.AddAsync(UserMapping.CreateDtoUser(user));

            if (user.Address != null)
            {
                var addressId = await addressRepository.AddAsync(AddressMapping.CreateDtoAddress(user.Address));

                await userAddressesRepository.AddAsync(AddressMapping.CreateUserAddressDTO(userId, addressId));
            }
        }
Beispiel #16
0
        public async void LeaveClick(object sender, EventArgs e)
        {
            familyTabPageViewModel.family.removeMember(familyTabPageViewModel.user.uid);
            familyTabPageViewModel.user.familyId = null;
            await familyRepository.AddAsync(familyTabPageViewModel.family);

            await userRepository.AddAsync(familyTabPageViewModel.user);

            GoInAddMode();
            await Device.InvokeOnMainThreadAsync(async() => { lstUsers.ItemsSource = familyTabPageViewModel.members; });

            await Device.InvokeOnMainThreadAsync(async() => { familyNameEntry.Text = ""; });

            await DisplayAlert("La tua famiglia", "Sei uscito correttamente dalla famiglia", "OK");

            Parent.BindingContext = familyTabPageViewModel;
        }
Beispiel #17
0
        public async Task when_adding_newuser_it_should_be_added_correctly_to_the_collection()
        {
            var             user       = new User(Guid.NewGuid(), "user", "test", "*****@*****.**", "secret");
            IUserRepository repository = new UserRepository();

            await repository.AddAsync(user);

            var exestingUser = await repository.GetAsync(user.Id);

            Assert.Equal(user, exestingUser);
        }
        public async Task <TLDialogs> AutoKickAsync()
        {
            var dialogs = await _messagesTL.GetDialogsAsync();

            if (dialogs?.dialogs == null || dialogs.dialogs.lists.Count == 0)
            {
                return(dialogs);
            }
            var autoKickChats = await _chatRepository.GetAutoKickAsync();

            foreach (var dialog in dialogs.dialogs.lists.Where(d => d.unread_count > 0 && d.peer is TLPeerChat).ToList())
            {
                var chatId = ((TLPeerChat)dialog.peer).chat_id;
                if (autoKickChats.All(c => c.Id != chatId))
                {
                    continue;
                }
                var users =
                    await _messagesTL.GetAddUserMessagesAsync(chatId, dialog.unread_count);

                foreach (var tlUser in users)
                {
                    var user = await _userRepository.GetUserByTLIdAsync(tlUser.id) ?? new User
                    {
                        Id = tlUser.id
                    };
                    UserService.CopyUserProps(user, tlUser, false);
                    if (user.UserId == 0)
                    {
                        await _userRepository.AddAsync(user);
                    }
                    else
                    {
                        await _userRepository.SaveChangesAsync();
                    }

                    try
                    {
                        await _chatTL.RemoveUserAsync(new Chat { Id = chatId }, user);
                    }
                    catch (InvalidOperationException ex)
                    {
                        if (!ex.Message.Equals("USER_NOT_PARTICIPANT", StringComparison.InvariantCultureIgnoreCase))
                        {
                            throw;
                        }
                    }
                }

                await _messagesTL.MarkUserMessagesAsReadAsync(new TLInputPeerChat { chat_id = chatId });
            }

            return(dialogs);
        }
Beispiel #19
0
 public async Task <ActionResult <string> > PostAsync([FromBody] UserEntity PEntity)
 {
     if (await _UserRepository.AddAsync(PEntity).ConfigureAwait(false) > 0)
     {
         return(Ok(PEntity));
     }
     else
     {
         return(Ok(PEntity));
     }
 }
Beispiel #20
0
        private static void InitData()
        {
            for (int i = 0; i < 50; i++)
            {
                var gender = FakeUtil.CreateGender();
                var item   = new User()
                {
                    Username   = FakeUtil.CreateUsername(5, 10),
                    Password   = FakeUtil.CreatePassword(),
                    Email      = FakeUtil.CreateEmail(),
                    Name       = FakeUtil.CreatePersonName(gender),
                    Gender     = gender,
                    Age        = FakeUtil.RandomInt(18, 50),
                    CreateTime = DateTime.Now
                };

                _userRepository.AddAsync(item).GetAwaiter().GetResult();
                Assert.True(true);
            }
        }
Beispiel #21
0
        public async Task CreateNewUser()
        {
            //Arrange
            User user = new User();

            user.Id        = 0;
            user.Username  = "******";
            user.Email     = "user1Email";
            user.Password  = SecurePasswordHasher.Hash("user1password");
            user.IsAdmin   = false;
            user.CreatedAt = DateTime.Now;

            //Act
            var addResult = await userRepository.AddAsync(user);

            //Assert
            Assert.IsNotNull(addResult);
            Assert.AreEqual(user.Username, addResult.Username);
            Assert.AreEqual(user.Email, addResult.Email);
            Assert.AreEqual(user.Password, addResult.Password);
        }
        public async Task Should_Throw_When_Add_Duplicate_Username()
        {
            IUserRepository userRepo = new UserRepository(
                _fxt.Database.GetCollection <User>("users")
                );

            await Assert.ThrowsAsync <DuplicateKeyException>(() =>
                                                             userRepo.AddAsync(new User {
                DisplayId = "CHuck"
            })
                                                             );
        }
Beispiel #23
0
 public async Task LoadImmage()
 {
     try
     {
         string path = DownloadImage(new Uri(await firebaseStorageService.GetFile(user.uid), UriKind.Absolute));
         user.photoURL = path;
         await userRepository.AddAsync(user);
     }
     catch (Exception e)
     {
         user.photoURL = "placeholder_profile.png";
     }
 }
Beispiel #24
0
        public async Task when_adding_new_user_it_should_be_added_correcty_to_the_list()
        {
            //Arrange
            var             user       = new User(Guid.NewGuid(), "user", "test", "*****@*****.**", "secret");
            IUserRepository repository = new UserRepository();
            //Act
            await repository.AddAsync(user);

            //Assert
            var existingUser = await repository.GetAsync(user.Id);

            Assert.Equal(user, existingUser);
        }
        public async Task Post_Login_Returns_Ok()
        {
            //Arrange
            string email    = "*****@*****.**";
            string password = "******";

            UserViewModel user = new UserViewModel()
            {
                Email       = email,
                FirstName   = "Atanas",
                LastName    = "Kambitov",
                Id          = 1,
                IsAdmin     = true,
                UniqueToken = Guid.NewGuid().ToString(),
                Lists       = new List <TodoListViewModel>(),
            };

            await _userRepository.AddAsync(user, password);

            _userRepository.CommitChanges();

            LoginViewModel model = new LoginViewModel
            {
                Email    = email,
                Password = password
            };

            //Act
            int usersCount = _userRepository.Count();
            var result     = await _authController.Post(model);

            var objectResponse = result as ObjectResult;

            //Assert
            Assert.Equal(1, usersCount);
            Assert.IsType <OkObjectResult>(result);
            Assert.Equal(200, objectResponse.StatusCode);
        }
        public async Task Should_Add_New_User()
        {
            // insert a new user into the collection
            User user;
            {
                IUserRepository userRepo = new UserRepository(
                    _fxt.Database.GetCollection <User>("users")
                    );
                user = new User
                {
                    FirstName      = "Charles",
                    DisplayId      = "chuck",
                    PassphraseHash = "some secret-PASS"
                };
                await userRepo.AddAsync(user);
            }

            // ensure user object is updated
            {
                Assert.Equal("Charles", user.FirstName);
                Assert.Equal("chuck", user.DisplayId);
                Assert.Equal("some secret-PASS", user.PassphraseHash);
                Assert.NotNull(user.Id);
                Assert.True(ObjectId.TryParse(user.Id, out _), "User ID should be a Mongo ObjectID.");
                Assert.InRange(user.JoinedAt, DateTime.UtcNow.AddSeconds(-5), DateTime.UtcNow);

                Assert.Null(user.LastName);
                Assert.Null(user.Token);
                Assert.Null(user.ModifiedAt);
            }

            // ensure user document is created in the collection
            {
                BsonDocument userDocument = _fxt.Database
                                            .GetCollection <BsonDocument>("users")
                                            .FindSync(FilterDefinition <BsonDocument> .Empty)
                                            .Single();

                Assert.Equal(
                    BsonDocument.Parse($@"{{
                        _id: ObjectId(""{user.Id}""),
                        name: ""chuck"",
                        pass: ""some secret-PASS"",
                        fname: ""Charles"",
                        joined: ISODate(""{user.JoinedAt:O}"")
                    }}"),
                    userDocument
                    );
            }
        }
        public async Task AddAsync_UniqueValidUser_AddedToList()
        {
            //Arange
            var             user           = new User(Guid.NewGuid(), "admin", "admin", "*****@*****.**", "pasword");
            IUserRepository userRepository = new UserRepository();

            //Act
            await userRepository.AddAsync(user);

            //Assert
            var existingUser = await userRepository.GetAsync("*****@*****.**");

            Assert.Equal(existingUser, user);
        }
Beispiel #28
0
        public async Task when_adding_new_user_it_should_be_added_correctly_to_the_list()
        {
            //Arrange - cały setup, przypisujemy zmienne, wartosci itp
            var             user       = new User(Guid.NewGuid(), "user", "test", "*****@*****.**", "secret");
            IUserRepository repository = new UserRepository();

            //Act - operacja, która ma zostać sprawdzona
            await repository.AddAsync(user);

            //Assert - sprawdzenie, czy test jest poprawny
            var existingUser = await repository.GetAsync(user.Id);

            Assert.Equal(user, existingUser);
        }
        public async Task <User> Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
            (string Salt, string Hashed)p = Password.Hash(request.Password);
            var user = await UserRepository.AddAsync(new User
            {
                Email    = request.Email,
                Password = p.Hashed,
                Salt     = p.Salt,
                Name     = request.Name,
                Created  = System.DateTime.Now
            });

            return(user);
        }
        public async Task WhenAddingNewUserThanItBeAddedCorrectlyToTheList()
        {
            // Arrange
            var             user = new User(Guid.NewGuid(), "user", "NewUser", "*****@*****.**", "tajneHasło 54%$");
            IUserRepository repo = new UserRepository();

            // Act
            await repo.AddAsync(user);

            var existingUser = await repo.GetAsync(user.Id);

            // Assert
            Assert.Equal(user, existingUser);
        }