Ejemplo n.º 1
0
        public IActionResult Auth([FromBody] UserToCreateDto user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            if (string.IsNullOrEmpty(user.Login) &&
                !user.Login.All(char.IsLetterOrDigit))
            {
                ModelState.AddModelError(nameof(UserToCreateDto.Login),
                                         "Login should contain only letters or digits.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var userEntity = Mapper.Map <User>(user);
            var userOnDb   = context.Users.Where(x => x.Login == userEntity.Login).FirstOrDefault();

            if (userOnDb == null || userOnDb.Password != userEntity.Password)
            {
                return(BadRequest()); //Нужно возвращать что-то нормальное, а не бедреквест
            }
            return(CreatedAtRoute(
                       new { userId = userOnDb.Id },
                       userOnDb.Id));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> CreateUser(UserToCreateDto model)
        {
            var auditScope = this.GetCurrentAuditScope();

            auditScope.Comment("Создание нового пользователя.");
            var auditAction = auditScope.Event.GetWebApiAuditAction();

            auditAction.ActionParameters = null;

            AppUser user = new AppUser()
            {
                UserName    = model.UserName,
                Email       = model.Email,
                PhoneNumber = model.PhoneNumber
            };

            var result = await _userManager.CreateAsync(user, model.Password);

            if (result == IdentityResult.Success)
            {
                return(Ok(user));
            }

            return(BadRequest(result.Errors));
        }
Ejemplo n.º 3
0
        public IActionResult Reg([FromBody] UserToCreateDto user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            if (string.IsNullOrEmpty(user.Login) &&
                !user.Login.All(char.IsLetterOrDigit))
            {
                ModelState.AddModelError(nameof(UserToCreateDto.Login),
                                         "Login should contain only letters or digits.");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var userEntity  = Mapper.Map <User>(user);
            var loginsUsers = context.Users.Select(x => x.Login).ToList();

            if (loginsUsers.Contains(userEntity.Login))
            {
                return(BadRequest()); //Нужно возвращать что-то нормальное, а не бедреквест
            }
            var createdUserEntity = context.Users.Add(userEntity);

            context.SaveChanges();

            return(CreatedAtRoute(
                       new { userId = createdUserEntity.Entity.Id },
                       createdUserEntity.Entity.Id));
        }
Ejemplo n.º 4
0
        public void Register(UserToCreateDto userToCreate)
        {
            userToCreate.Username = userToCreate.Username.ToLower();

            if (_authRepository.Any(x => x.Username == userToCreate.Username))
            {
                throw new Exception("Já existe alguem com esse Nome de Usuário.");
            }

            var userToAdd = _mapper.Map <User>(userToCreate);

            CreatePasswordHash(userToCreate.Password, out var passwordHash, out var passwordSalt);

            userToAdd.LocalidadeId = GetLocalizacao(userToCreate.Cep).Result;

            userToAdd.PasswordHash = passwordHash;
            userToAdd.PasswordSalt = passwordSalt;

            _authRepository.Add(userToAdd);

            if (!Commit())
            {
                throw new Exception("Houve algum erro ao salvar no Banco de Dados.");
            }
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Register(UserToCreateDto model)
        {
            var user    = new User();
            var newuser = await _authService.Register(user.CreateUser(model), model.Password);

            UserDto userDto = _mapper.Map <UserDto>(newuser);

            return(Ok(userDto));
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> PostUser(UserToCreateDto userToCreateDto)
        {
            var userToCreate = _mapper.Map <User>(userToCreateDto);
            await _context.Users.AddAsync(userToCreate);

            await _context.SaveChangesAsync();

            return(Ok(userToCreate));
        }
Ejemplo n.º 7
0
        public static User CreateUser(this User u, UserToCreateDto model)
        {
            u.Id      = Guid.NewGuid().ToString();
            u.Email   = model.Email;
            u.Name    = model.Name;
            u.Surname = model.Surname;

            return(u);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> CreateUserAsync([FromBody] UserToCreateDto userToCreateDto)
        {
            var userEntity = mapper.Map <UserEntity>(userToCreateDto);

            userEntity = await userRepository.InsertAsync(userEntity);

            var userToSendDto = mapper.Map <UserToSendDto>(userEntity);

            return(CreatedAtRoute("GetUserById", new CreatedRouteValue(userToSendDto.Id), userToSendDto));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Post(UserToCreateDto user)
        {
            UserDto createdUser = await _service.CreateUser(user);

            if (createdUser == null)
            {
                return(StatusCode(400));
            }
            return(StatusCode(200, createdUser));
        }
Ejemplo n.º 10
0
        public async Task <UserDto> CreateUserAsync(UserToCreateDto user)
        {
            GetClient();
            UserDto             createdUser = null;
            HttpResponseMessage response    = await client.PostAsJsonAsync("api/users/", user);

            if (response.IsSuccessStatusCode)
            {
                createdUser = await response.Content.ReadAsAsync <UserDto>();
            }
            return(createdUser);
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> Register(UserToCreateDto userToCreateDto)
        {
            if (await _auth.IsUserExist(userToCreateDto.Username))
            {
                return(BadRequest("Tên đăng nhập đã tồn tại, vui lòng thử lại"));
            }

            var user = _mapper.Map <User>(userToCreateDto);
            await _auth.Register(user, userToCreateDto.Password);

            return(StatusCode(201));
        }
Ejemplo n.º 12
0
        public IActionResult Register(UserToCreateDto userToCreate)
        {
            try
            {
                _authService.Register(userToCreate);

                return(Created("", new { username = userToCreate.Username }));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception));
            }
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> AddUser([FromBody] UserToCreateDto userToCreteDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            using (var session = _store.OpenAsyncSession())
            {
                var user = await session.Query <User>()
                           .Where(u => u.Email.Equals(userToCreteDto.Email, StringComparison.OrdinalIgnoreCase))
                           .FirstOrDefaultAsync();

                if (user != null)
                {
                    return(BadRequest(new { error = "The email is already in use." }));
                }

                var dbUser = _mapper.Map <User>(userToCreteDto);
                dbUser.Color = await GetColor();

                var temporaryPassword = RandomPasswordGenerator.GeneratePassword(15);
                var salt           = Convert.ToBase64String(PasswordHasher.GenerateSalt());
                var hashedPassword = PasswordHasher.HashPassword(temporaryPassword, Convert.FromBase64String(salt));
                dbUser.Salt = salt;
                dbUser.TemporaryPassword = hashedPassword;

                await session.StoreAsync(dbUser);

                await session.SaveChangesAsync();

                string username = FormatUsername(dbUser.Email);

                string message = $"<b>Dear {dbUser.FirstName}</b></br><p>You're receiving this message because your Scheduler Account has been created.</p><p>Your <b>username</b>: {username}</p><p>Your <b>first-time login password</b>: {temporaryPassword}</p><p>Follow the link below to change your password and log in to Scheduler application:</p><p><a href={_dataServiceConfiguration.ClientUrl}>Login</a></p><p>Best</p><p>Scheduler Team</p>";

                _schedulerMailer.SendMail("Scheduler-Notifications", dbUser.Email, "Scheduler Account", message, _dataServiceConfiguration.MailBoxPassword);

                var userToReturn = _mapper.Map <PostCreationUserToReturnDto>(dbUser);

                return(CreatedAtRoute("GetUser", new { userId = dbUser.Id }, userToReturn));
            }
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> CreateUser([FromBody] UserToCreateDto dto)
        {
            if (dto is null)
            {
                return(BadRequest());
            }

            var outerFacingModelUser = _userCommand.ExecuteAddResource(dto);

            if (!(await _userCommand.ExecuteSaveAsync()))
            {
                throw new Exception("There was a problem with saving the user resource");
            }

            outerFacingModelUser.ShapeData(null)
            .TryAdd("links", CreateLinks(outerFacingModelUser.Id, null));

            return(CreatedAtRoute("GetUser",
                                  new { id = outerFacingModelUser.Id }, outerFacingModelUser));
        }
Ejemplo n.º 15
0
        public async Task <UserDto> CreateUser(UserToCreateDto userToCreate)
        {
            byte[] pswHash, pswSalt;
            CreatePasswordHash(userToCreate.Psw, out pswHash, out pswSalt);

            Address address = new Address
            {
                Country     = userToCreate.Address.Country,
                City        = userToCreate.Address.City,
                PostalCode  = userToCreate.Address.PostalCode,
                Street      = userToCreate.Address.Street,
                HouseNumber = userToCreate.Address.HouseNumber,
                BoxNumber   = userToCreate.Address.BoxNumber
            };

            User user = new User
            {
                FirstName   = userToCreate.FirstName,
                LastName    = userToCreate.LastName,
                Email       = userToCreate.Email.ToLower(),
                PhoneNumber = userToCreate.PhoneNumber,
                PswHash     = pswHash,
                PswSalt     = pswSalt,
                Address     = address
            };

            var createdUser = ConvertToUserDto(await AddAsync(user));

            if (createdUser != null)
            {
                ProjectUser projectUser = new ProjectUser
                {
                    ProjectId = 3,
                    UserId    = createdUser.ID
                };
                await AddAsync(projectUser);
                await AddUserToCompany(3, createdUser.Email);
            }

            return(createdUser);
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Register(UserToCreateDto userForRegister)
        {
            //validate the request  - It will be used we dont use apiController attribute else we have to use modelstate.isVaid

            string username = userForRegister.Username, password = userForRegister.Password;

            username = username.ToLower();

            if (await _repo.UserExists(username))
            {
                return(BadRequest("Username already exist!"));
            }

            var userToCreate = new User
            {
                Username = username
            };

            var createdUser = await _repo.Register(userToCreate, password);

            return(StatusCode(201));
        }
Ejemplo n.º 17
0
        public async Task <ActionResult <UserDto> > CreateUser(UserToCreateDto userToCreate)
        {
            if (CheckEmailExistsAsync(userToCreate.Email).Result.Value)
            {
                return(new BadRequestObjectResult(new ApiValidationErrorResponse
                {
                    Errors = new[]
                    { "Email address is in use" }
                }));
            }
            var user = new AppUser
            {
                DisplayName = userToCreate.DisplayName,
                FirstName   = userToCreate.FirstName,
                LastName    = userToCreate.LastName,
                Birthday    = userToCreate.Birthday,
                Gender      = userToCreate.Gender,
                Phone       = userToCreate.Phone,
                Email       = userToCreate.Email,
                UserName    = userToCreate.Email,
            };
            var result = await _userManager.CreateAsync(user, userToCreate.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(new ApiResponse(400)));
            }
            return(new UserDto
            {
                DisplayName = user.DisplayName,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Birthday = user.Birthday,
                Gender = user.Gender,
                Phone = user.Phone,
                Token = await _tokenService.CreateToken(user),
                Email = user.Email
            });
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> CreateUserWithRoles(UserToCreateDto userToCreate)
        {
            var userToSave = new User
            {
                UserName       = userToCreate.UserName,
                FirstName      = userToCreate.Password,
                EmailConfirmed = true,
                ValidatedCode  = true
            };

            IdentityResult result = _userManager.CreateAsync(userToSave, userToCreate.Password).Result;

            if (result.Succeeded)
            {
                var userCreated = _userManager.FindByNameAsync(userToCreate.UserName).Result;
                var res         = _userManager.AddToRolesAsync(userCreated, userToCreate.Roles).Result;
                if (res.Succeeded)
                {
                    var userToReturn = await(from user in _context.Users
                                             where user.Id == userCreated.Id

                                             select new
                    {
                        Id       = user.Id,
                        UserName = user.UserName,
                        Roles    = (from userRole in user.UserRoles
                                    join role in _context.Roles
                                    on userRole.RoleId
                                    equals role.Id
                                    select role.Name).ToList()
                    }).FirstOrDefaultAsync();
                    return(Ok(userToReturn));
                }
                return(BadRequest("Impossible d'ajouter l'utilisateur"));
            }
            return(BadRequest());
        }
Ejemplo n.º 19
0
        static void Main()
        {
            //Create address
            AddressToCreateDto createdAddress = new AddressToCreateDto
            {
                Country     = "Belgium",
                City        = "Brussel",
                PostalCode  = "1000",
                Street      = "testStraat",
                HouseNumber = "20"
            };

            //Create user
            UserToCreateDto createdUser = new UserToCreateDto
            {
                FirstName   = "Mich",
                LastName    = "dg",
                Email       = "*****@*****.**",
                PhoneNumber = "+3256798487",
                Psw         = "hallo",
                Address     = createdAddress
            };

            //Update address
            AddressToUpdateDto updatedAddress = new AddressToUpdateDto
            {
                Country     = "Belgium",
                City        = "Brussel",
                PostalCode  = "1000",
                Street      = "testStraat1",
                HouseNumber = "35"
            };

            //Update user
            UserToUpdateDto updatedUser = new UserToUpdateDto
            {
                FirstName   = "Michael",
                LastName    = "DG",
                Email       = "*****@*****.**",
                PhoneNumber = "+3256798489",
                Address     = updatedAddress
            };

            //Login
            UserToLoginDto login = new UserToLoginDto
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            //Create company
            CompanyToCreateDto createdCompany = new CompanyToCreateDto
            {
                Name    = "Microsoft1",
                Address = createdAddress
            };

            //Update company
            CompanyToUpdateDto updatedCompany = new CompanyToUpdateDto
            {
                Name    = "Microsoft 2",
                Address = updatedAddress
            };

            //Create companyrole
            CompanyRoleToCreateDto createdCompanyRole = new CompanyRoleToCreateDto
            {
                Name           = "CompanyRole1",
                Description    = "It's just a test",
                IsDefault      = true,
                ManageCompany  = true,
                ManageUsers    = false,
                ManageProjects = true,
                ManageRoles    = true
            };

            //Update companyrole
            CompanyRoleToUpdateDto updatedCompanyRole = new CompanyRoleToUpdateDto
            {
                Name           = "CompanyRole1Updated",
                Description    = "It's just a test for something",
                IsDefault      = true,
                ManageCompany  = true,
                ManageUsers    = true,
                ManageProjects = true,
                ManageRoles    = true
            };

            //Create project
            ProjectToCreateDto createdProject = new ProjectToCreateDto
            {
                CompanyID   = 1,
                Name        = "Tim",
                Description = "desc"
            };

            //Update project
            ProjectToUpdateDto updatedProject = new ProjectToUpdateDto
            {
                CompanyID   = 2,
                Name        = "Kevin",
                Description = "desc 2"
            };


            //Testen API calls
            UserServices        userServices        = new UserServices();
            CompanyServices     companyServices     = new CompanyServices();
            ProjectServices     projectServices     = new ProjectServices();
            CompanyRoleServices companyRoleServices = new CompanyRoleServices();
            LogServices         logServices         = new LogServices();
            SessionServices     sessionServices     = new SessionServices();

            UserDto        user1 = new UserDto();
            CompanyDto     c     = new CompanyDto();
            CompanyRoleDto cr    = new CompanyRoleDto();
            ProjectDto     p     = new ProjectDto();


            //Userservices  //OK

            //user1 = userServices.GetUserByIdAsync(1).GetAwaiter().GetResult();
            //List<UserDto> userlist = userServices.GetAllUsersAsync().GetAwaiter().GetResult();
            //user1 = userServices.CreateUserAsync(createdUser).GetAwaiter().GetResult();
            //user1 = userServices.UpdateUserByIdAsync(updatedUser, 1).GetAwaiter().GetResult();
            //user1 = userServices.DeleteUserByIdAsync(3).GetAwaiter().GetResult();
            //List<LogDto> user = userServices.GetAllUserLogsAsync(1).GetAwaiter().GetResult();
            //List<UserDto> users = userServices.GetUserByEmailAsync("*****@*****.**").GetAwaiter().GetResult();
            //List<LogDto> lk = userServices.GetAllUserLogsAsync(5).GetAwaiter().GetResult();


            //Sessionservices  //OK

            //string str = sessionServices.CreateSession(login);
            //string str = sessionServices.DeleteSessionAsync().GetAwaiter().GetResult();


            //Companyservices  //OK

            //List<CompanyDto> companylist = companyServices.GetAllCompaniesAsync().GetAwaiter().GetResult();
            //c = companyServices.GetCompanyByIdAsync(1).GetAwaiter().GetResult();
            //c = companyServices.CreateCompanyAsync(createdCompany).GetAwaiter().GetResult();
            //c = companyServices.UpdateCompanyByIdAsync(updatedCompany, 1).GetAwaiter().GetResult();
            //List<UserDto> cl = companyServices.GetUsersFromCompanyByIdAsync(1).GetAwaiter().GetResult();
            //bool b = companyServices.AddUserToCompanyByIdAsync(1, 8).GetAwaiter().GetResult();


            //CompanyRoleservices  //OK

            //cr = companyRoleServices.CreateCompanyRoleAsync(createdCompanyRole, 1).GetAwaiter().GetResult();
            //List<CompanyRoleDto> crlist = companyRoleServices.GetAllCompanyRolesAsync(1).GetAwaiter().GetResult();
            //cr = companyRoleServices.GetCompanyRoleByIdAsync(1, 3).GetAwaiter().GetResult();
            //cr = companyRoleServices.UpdateCompanyRoleByIdAsync(updatedCompanyRole, 1, 3).GetAwaiter().GetResult();


            //Projectservices  //OK

            //bool bp = projectServices.UpdateProjectByIdAsync(updatedProject, 1).GetAwaiter().GetResult();
            //List<ProjectDto> projects = companyServices.GetAllCompanyProjectsAsync(1).GetAwaiter().GetResult();
            //List<ProjectDto> projects = userServices.GetAllUserProjectsAsync(1).GetAwaiter().GetResult();
            //bool pu = projectServices.RemoveUserToProjectAsync(1, 1).GetAwaiter().GetResult();
            //bool u = projectServices.AddUserToProjectAsync(1, "*****@*****.**").GetAwaiter().GetResult();
            //bool u = projectServices.RemoveUserToProjectAsync(1, 7).GetAwaiter().GetResult();
        }
Ejemplo n.º 20
0
        private async void ClickRegister(object sender, EventArgs e)
        {
            List <Entry> NoErrors = new List <Entry>();

            List <Entry> Errors = new List <Entry>();

            //first name
            if (CheckStringIsFilled(firstname.Text))
            {
                Errors.Add(firstname);
                firstnameError.Text      = "This field is required!";
                firstnameError.IsVisible = true;
            }
            else
            {
                NoErrors.Add(firstname);
                firstnameError.IsVisible = false;
            }

            //last name
            if (CheckStringIsFilled(lastname.Text))
            {
                Errors.Add(lastname);
                lastnameError.Text      = "This field is required!";
                lastnameError.IsVisible = true;
            }
            else
            {
                NoErrors.Add(lastname);
                lastnameError.IsVisible = false;
            }

            //email
            if (CheckStringIsFilled(email.Text))
            {
                Errors.Add(email);
                emailError.Text      = "This field is required!";
                emailError.IsVisible = true;
            }
            else
            {
                if (CheckEmail(email.Text))
                {
                    NoErrors.Add(email);
                    emailError.IsVisible = false;
                }
                else
                {
                    Errors.Add(email);
                    emailError.Text      = "E-mail is not correct!";
                    emailError.IsVisible = true;
                }
            }

            //phone number
            if (CheckStringIsFilled(phonenumber.Text))
            {
                Errors.Add(phonenumber);
                phoneError.Text      = "This field is required!";
                phoneError.IsVisible = true;
            }
            else
            {
                if (CheckPhone(phonenumber.Text))
                {
                    NoErrors.Add(phonenumber);
                    phoneError.IsVisible = false;
                }
                else
                {
                    Errors.Add(phonenumber);
                    phoneError.Text      = "Phone number is not correct!";
                    phoneError.IsVisible = true;
                }
            }

            //Street name
            if (CheckStringIsFilled(streetname.Text))
            {
                Errors.Add(streetname);
                streetnameError.Text      = "This field is required!";
                streetnameError.IsVisible = true;
            }
            else
            {
                NoErrors.Add(streetname);
                streetnameError.IsVisible = false;
            }

            //House number
            if (CheckStringIsFilled(housenumber.Text))
            {
                Errors.Add(housenumber);
                housenumberError.Text      = "This field is required!";
                housenumberError.IsVisible = true;
            }
            else
            {
                NoErrors.Add(housenumber);
                housenumberError.IsVisible = false;
            }

            //Country
            if (CheckStringIsFilled(country.Text))
            {
                Errors.Add(country);
                countryError.Text      = "This field is required!";
                countryError.IsVisible = true;
            }
            else
            {
                NoErrors.Add(country);
                countryError.IsVisible = false;
            }

            //Postal code
            if (CheckStringIsFilled(postalcode.Text))
            {
                Errors.Add(postalcode);
                postalcodeError.Text      = "This field is required!";
                postalcodeError.IsVisible = true;
            }
            else
            {
                if (CheckPostalCode(postalcode.Text))
                {
                    NoErrors.Add(postalcode);
                    postalcodeError.IsVisible = false;
                }
                else
                {
                    Errors.Add(postalcode);
                    postalcodeError.Text      = "Postal code is not correct!";
                    postalcodeError.IsVisible = true;
                }
            }

            //City
            if (CheckStringIsFilled(city.Text))
            {
                Errors.Add(city);
                cityError.Text      = "This field is required!";
                cityError.IsVisible = true;
            }
            else
            {
                NoErrors.Add(city);
                cityError.IsVisible = false;
            }

            //Password
            if (CheckStringIsFilled(password.Text))
            {
                Errors.Add(password);
                passwordError.Text      = "This field is required!";
                passwordError.IsVisible = true;
            }
            else
            {
                if (CheckPassword(password.Text))
                {
                    NoErrors.Add(password);
                    passwordError.IsVisible = false;
                }
                else
                {
                    Errors.Add(password);
                    passwordError.Text      = "Password must between 8 and 20 characters,and must contain atleast one digit, atleast one upper case and atleast one lower case and no whitespace!";
                    passwordError.IsVisible = true;
                }
            }

            //Confirm password
            if (CheckpasswordEquality(password.Text, confirmpassword.Text))
            {
                NoErrors.Add(confirmpassword);
                confirmpasswordError.IsVisible = false;
            }
            else
            {
                Errors.Add(confirmpassword);
                confirmpasswordError.Text      = "The passwords are not equal!";
                confirmpasswordError.IsVisible = true;
            }

            /*
             * if (Errors.Count == 0)
             * {
             *  await DisplayAlert("Message", $"No errors found! Errors: {Errors.Count}", "Ok");
             * }
             */

            if (Errors.Count() == 0)
            {
                UserServices userServices = new UserServices();

                UserToCreateDto user = new UserToCreateDto
                {
                    Email       = email.Text,
                    Psw         = password.Text,
                    FirstName   = firstname.Text,
                    LastName    = lastname.Text,
                    PhoneNumber = phonenumber.Text,
                    Address     = new AddressToCreateDto
                    {
                        Street      = streetname.Text,
                        HouseNumber = housenumber.Text,
                        Country     = country.Text,
                        PostalCode  = postalcode.Text,
                        City        = city.Text,
                        BoxNumber   = boxnumber.Text
                    }
                };
                buttonRegister.IsEnabled = false;
                await userServices.CreateUserAsync(user);

                await Navigation.PopModalAsync();

                //Application.Current.MainPage = new Login();
            }

            SetError(Errors);
            SetNoError(NoErrors);
        }