public async Task SaveUser(RegisterUserDTO model)
        {
            var user = Mapper.Map <UserData>(model);

            DbContext.UserDatas.Add(user);
            await DbContext.SaveChangesAsync();
        }
Пример #2
0
        public async Task <ActionResult> RegisterUser(RegisterUserDTO registerUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = new IdentityUser
            {
                UserName       = registerUser.Email,
                Email          = registerUser.Email,
                EmailConfirmed = true
            };

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

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, false);

                return(Ok(new {
                    user = registerUser,
                    token = GenerateJwt()
                }));
            }

            return(BadRequest(new
            {
                statusCode = 400,
                errors = result.Errors
            }));
        }
Пример #3
0
        public RegisterUserDTO UserForToken(string token)
        {
            RegisterUserDTO response = null;

            using (var entities = new UCAInvestDBEntities())
            {
                var dbResponse = entities.user_tokens.SingleOrDefault(t => t.token == token);
                if (dbResponse != null)
                {
                    var expireTime = TimeFunctions.UnixTimeStampToDateTime(Convert.ToInt64(dbResponse.expire_timestamp));

                    if (expireTime < DateTime.Now) // Token expired, has to delete
                    {
                        entities.user_tokens.Remove(dbResponse);
                        entities.SaveChanges();
                    }
                    else
                    {
                        var userLinked = dbResponse.users;
                        var config     = new MapperConfiguration(cfg => {
                            cfg.CreateMap <User, RegisterUserDTO>();
                        });

                        IMapper iMapper = config.CreateMapper();

                        response = iMapper.Map <User, RegisterUserDTO>(userLinked);
                    }
                }
            }

            return(response);
        }
Пример #4
0
        public async Task <IdentityResult> RegisterAdmin(RegisterUserDTO user)
        {
            Admin userToInsert = UserToUserDTOConverters.RegisterUserDTOtoAdmin(user);

            logger.Info("Registering admin.");
            return(await db.AuthRepository.RegisterAdmin(userToInsert, user.Password));
        }
Пример #5
0
        public async Task <IdentityResult> RegisterParent(RegisterUserDTO user)
        {
            Parent userToInsert = UserToUserDTOConverters.RegisterUserDTOtoParent(user);

            logger.Info("Registering parent.");
            return(await db.AuthRepository.RegisterParent(userToInsert, user.Password));
        }
Пример #6
0
        public async Task <RegisterUserResult> RegisterUser(RegisterUserDTO register)
        {
            if (IsUserExistByEmail(register.Email))
            {
                return(RegisterUserResult.EmailExist);
            }

            var user = new User
            {
                Email           = register.Email.SanitizeText(),
                Address         = register.Address.SanitizeText(),
                FirstName       = register.FirstName.SanitizeText(),
                LastName        = register.LastName.SanitizeText(),
                EmailActiveCode = Guid.NewGuid().ToString(),
                Password        = _passwordHelper.EncodePasswordMd5(register.Password)
            };

            await _userRepository.AddEntity(user);

            await _userRepository.SaveChanges();


            #region Sending Activated Email
            var body = await _renderView.RenderToStringAsync("Email/_ActivateAccount", user);

            _mailSender.Send("*****@*****.**", "تست فعالسازی", body);
            #endregion

            return(RegisterUserResult.Success);
        }
Пример #7
0
        public async Task <ActionResult> RegisterUser(RegisterUserDTO registerUserDTO)
        {
            if (!ModelState.IsValid)
            {
                return(CustomResponse(ModelState));
            }

            var user = new IdentityUser
            {
                UserName       = registerUserDTO.Email,
                Email          = registerUserDTO.Email,
                EmailConfirmed = true
            };

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

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, false);

                return(CustomResponse(await GenerateJWT(user.Email)));
            }
            foreach (var error in result.Errors)
            {
                NotifyError(error.Description);
            }

            return(CustomResponse(registerUserDTO));
        }
Пример #8
0
        public async Task <ActionResult> RegisterNew([FromBody] RegisterUserDTO registerUserDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(e => e.Errors)));
            }

            var user = new IdentityUser
            {
                UserName       = registerUserDTO.Email,
                Email          = registerUserDTO.Email,
                EmailConfirmed = true
            };

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

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            await _singnInManeger.SignInAsync(user, false);


            var loginUser = new AccessManager()
            {
                User = new LoginUserDTO {
                    Email = registerUserDTO.Email, Password = registerUserDTO.Password
                },
                Token = await GerarJWT(registerUserDTO.Email)
            };

            return(Ok(loginUser));
        }
Пример #9
0
        public async Task <IActionResult> Register([FromBody] RegisterUserDTO registration)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            User newUser = new User
            {
                Email    = registration.Email,
                UserName = registration.Email,
                Id       = registration.Email,
            };

            IdentityResult result = await _userManager.CreateAsync(newUser, registration.Password);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Пример #10
0
        public async Task <ActionResult> Cadastrar(RegisterUserDTO registerUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new IdentityUser
            {
                UserName       = registerUser.Email,
                Email          = registerUser.Email,
                EmailConfirmed = false
            };

            //cria usuario na base com senha criptografada
            var result = await _userManager.CreateAsync(user, registerUser.Password);

            if (result.Succeeded)
            {
                await SendConfirmEmail(user);

                return(Ok(result.Succeeded));
            }

            return(BadRequest(ErrorResponse.FromIdentity(result.Errors.ToList())));
        }
Пример #11
0
        public async Task <string> Register(string userName, string email, string password)
        {
            using (var client = new HttpClient())
            {
                RegisterUserDTO registerUser = new RegisterUserDTO
                {
                    UserName = userName,
                    Email    = email,
                    Password = password
                };

                InitializeClient(client);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("api/account"));

                var content = new StringContent(JsonConvert.SerializeObject(registerUser), Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync($"{BaseUrl}/api/account", content);

                if (response.IsSuccessStatusCode)
                {
                    return("Success");
                }
                else
                {
                    var serializer = new DataContractJsonSerializer(typeof(string));
                    return((string)serializer.ReadObject(await response.Content.ReadAsStreamAsync()));
                }
            }
        }
Пример #12
0
        public IActionResult Register([FromBody] RegisterUserDTO registerUserDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            User newUser = new User()
            {
                Email       = registerUserDTO.Email,
                Country     = registerUserDTO.Country,
                DateOfBirth = registerUserDTO.DateOfBirth.HasValue ? registerUserDTO.DateOfBirth : DateTime.Now,
                isActive    = "active",
                RoleId      = registerUserDTO.RoleId
            };

            var passwordHash = _passwordHasher.HashPassword(newUser, registerUserDTO.PasswordHash);

            newUser.PasswordHash = passwordHash;

            _articleContext.Users.Add(newUser);
            _articleContext.SaveChanges();

            _logger.LogWarning($"Dodano nowego uzytkownika - {newUser.Email}, RoleID - {newUser.RoleId}");

            return(Ok());
        }
Пример #13
0
        public async Task <ActionResult <UserDTO> > Register(RegisterUserDTO userDTO)
        {
            if (await ExistUser(userDTO.Username))
            {
                return(BadRequest("Username is taken."));
            }
            var user = _mapper.Map <AppUser>(userDTO);

            user.CreatedDate = DateTime.UtcNow;
            user.UserName    = userDTO.Username.ToLower();
            var result = await _usermanager.CreateAsync(user, userDTO.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            result = await _usermanager.AddToRoleAsync(user, "Member");

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            return(new UserDTO
            {
                Username = user.UserName,
                Token = await _tokenService.CreateToken(user),
                KnownAs = user.KnownAs,
                Gender = user.Gender
            });
        }
Пример #14
0
        public Result <User> Insert(RegisterUserDTO userDto)
        {
            var user   = _mapper.Map <User>(userDto);
            var result = Validate(user);

            if (!result.Success)
            {
                return(result);
            }

            // Senha forte não é mais obrigatória.

            if (_repository.Any(x => x.Email == user.Email))
            {
                throw new ShareBookException("Usuário já possui email cadastrado.");
            }

            // LGPD - CONSENTIMENTO DOS PAIS.
            if (userDto.Age < 12)
            {
                ParentAprovalStartFlow(userDto, user);
            }

            user.Email = user.Email.ToLowerInvariant();
            if (result.Success)
            {
                user         = GetUserEncryptedPass(user);
                result.Value = UserCleanup(_repository.Insert(user));
            }
            return(result);
        }
Пример #15
0
        public ActionResult Register([FromBody] RegisterUserDTO credentials)
        {
            if (ModelState.IsValid)
            {
                var result = _BLL.Register(credentials);
                if (result.Success)
                {
                    DateTime expiration = DateTime.Now.AddMinutes(_JWTExpirationMinutes);

                    User user = _BLL.GetUser(credentials.Email);



                    return(Ok(new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(GenerateToken(user.UserName, user.IntId))
                    }));
                }
                else
                {
                    return(BadRequest(result.ErrorMessage));
                }
            }
            else
            {
                return(BadRequest());
            }
        }
Пример #16
0
        public IdentityResult RegisterUser(RegisterUserDTO sent, DateTime?date = null)
        {
            if (date.HasValue == false)
            {
                date = DateTime.Now;
            }

            var user = new User()
            {
                UserName    = sent.Email,
                FirstName   = protector.Protect(sent.FirstName),
                LastName    = protector.Protect(sent.LastName),
                Email       = sent.Email,
                PhoneNumber = protector.Protect(sent.PhoneNumber),
                Activity    = new List <Activity> {
                    new Activity()
                    {
                        Date    = date.Value,
                        Type    = ActivityType.AccountCreate,
                        Message = "Account created"
                    }
                },
                DateCreated = date.Value
            };

            return(userManager.CreateAsync(user, sent.Password).Result);
        }
Пример #17
0
        public async Task <ActionResult> Registrar(RegisterUserDTO registerUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Modelo de entrada inválido."));
            }

            var user = new IdentityUser
            {
                UserName       = registerUser.Email,
                Email          = registerUser.Email,
                EmailConfirmed = true
            };

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

            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, false);

                return(Ok(await this.GerarJwt(registerUser.Email)));
            }

            foreach (var error in result.Errors)
            {
                BadRequest(error.Description);
            }

            return(BadRequest(registerUser));
        }
Пример #18
0
        public async Task <IActionResult> Post([FromBody] RegisterUserDTO registerUserDTO)
        {
            var user = new ApplicationUser
            {
                UserName = registerUserDTO.UserName,
                Email    = registerUserDTO.Email
            };

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

            if (!string.IsNullOrEmpty(registerUserDTO.Level))
            {
                await _userManager.AddClaimAsync(
                    user,
                    new Claim(nameof(registerUserDTO.Level),
                              registerUserDTO.Level)
                    );
            }

            if (result.Succeeded)
            {
                return(Ok());
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    return(BadRequest(error.Code));
                }
                return(BadRequest());
            }
        }
Пример #19
0
        public async Task <ServiceResult> Register(RegisterUserDTO model)
        {
            ServiceResult result = new ServiceResult();
            User          user   = new User()
            {
                Email            = model.Email,
                BirthdayDate     = model.BirthdayDate,
                RegistrationDate = DateTime.Now,
                UserName         = model.Email
            };
            var createdResult = await _userManager.CreateAsync(user, model.Password);

            if (createdResult.Succeeded)
            {
                await _signInManager.SignInAsync(user, false);

                result.Status = ServiceResultStatus.Success;
            }
            else
            {
                foreach (var error in createdResult.Errors)
                {
                    var errorDescription = error.Description;
                    result.Errors.Add(error);
                }
            }
            return(result);
        }
Пример #20
0
        public async Task <ActionResult <LoginRegisterUserOutputDTO> > Register(RegisterUserDTO registerUser)
        {
            if (await ExistsUser(registerUser.UserName))
            {
                return(BadRequest("Username has been already used"));
            }

            using var hmac = new HMACSHA512();

            AppUser appUser = _mapper.Map <AppUser>(registerUser);

            appUser.UserName     = registerUser.UserName.ToLower();
            appUser.PasswordHash = await hmac.ComputeHashAsync(new MemoryStream(Encoding.UTF8.GetBytes(registerUser.Password)));

            appUser.PasswordSalt = hmac.Key;

            _context.Add(appUser);
            await _context.SaveChangesAsync();

            return(new LoginRegisterUserOutputDTO
            {
                UserName = appUser.UserName,
                Token = _tokenService.CreateToken(appUser),
                KnownAs = appUser.KnownAs,
                Gender = appUser.Gender
            });
        }
Пример #21
0
        public async Task <ServiceResponse <GetLoginDTO> > Register(RegisterUserDTO register)
        {
            var serviceResponse = new ServiceResponse <GetLoginDTO>();

            try
            {
                User user = _mapper.Map <User>(register);

                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(register.Password, out passwordHash, out passwordSalt);

                user.PasswordHash = passwordHash;
                user.PasswordSalt = passwordSalt;

                await _repository.AddAsync(user);

                serviceResponse.Data = new GetLoginDTO()
                {
                    Token = GenerateToken(user)
                };
            }
            catch (Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.Message;
            }

            return(serviceResponse);
        }
Пример #22
0
        public async Task <IActionResult> PostRegisterUser([FromBody] RegisterUserDTO newUser)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                IdentityResult result = await _authRepository.CreateUserAsync(newUser);

                if (!result.Succeeded)
                {
                    return(BadRequest(result.Errors));
                }

                await _authRepository.CreateRoleAsync(newUser.Role);

                User user = await _authRepository.GetUserAsync(newUser.Username);

                await _authRepository.AddUserToRoleAsync(user, newUser.Role);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Unexpected error while creating user: {ex.Message}");
                return(StatusCode(500, $"An unexpected error has occurred: {ex.Message}"));
            }
        }
Пример #23
0
        public async Task <IdentityResult> RegisterTeacher(RegisterUserDTO user)
        {
            Teacher userToInsert = UserToUserDTOConverters.RegisterUserDTOtoTeacher(user);

            logger.Info("Registering teacher.");
            return(await db.AuthRepository.RegisterTeacher(userToInsert, user.Password));
        }
Пример #24
0
        public async Task <ActionResult <UserAccessViewModel> > PostUser([FromBody] RegisterUserDTO dto)
        {
            if (_context.Users.Any(o => o.Login == dto.Username || o.Email == dto.Email))
            {
                return(Conflict(new ErrorViewModel {
                    ErrorText = "User already exists"
                }));
            }

            var user = new User
            {
                Email    = dto.Email,
                Login    = dto.Username,
                Password = dto.Password
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            var view = new UserViewModel
            {
                Email = user.Email,
                Id    = user.Id,
                Login = user.Login
            };

            return(CreatedAtAction(nameof(Token), new { Username = user.Login, user.Password }, view));
        }
Пример #25
0
        public async Task <string> InsertUserAsync(RegisterUserDTO model)
        {
            var exist = await this.CheckLoginAndEmailForExistAsync(model.Email, model.Login);

            if (exist)
            {
                throw new Exception("Login or email already exists.");
            }

            var user = new User {
                Login     = model.Login,
                Email     = model.Email,
                Password  = await this.m_security.EncryptPasswordAsync(model.Password),
                Role      = UserRoles.User,
                CreatedBy = model.Login,
                FirstName = model.Firstname,
                LastName  = model.Lastname,
                Active    = true
            };

            await this.Repository.CreateAsync(user);

            if (user.Id <= 0)
            {
                throw new Exception("Registration error.");
            }

            return(await this.m_security.GetTokenAsync(new LoginUserDTO { Login = user.Login, Password = model.Password }, true));
        }
Пример #26
0
        public User RegisterUser(RegisterUserDTO registerUserDTO)
        {
            var userEntity = new User(registerUserDTO.firstName, registerUserDTO.lastName, registerUserDTO.eMail, registerUserDTO.plainPassword);

            _users.InsertOne(userEntity);
            return(userEntity);
        }
Пример #27
0
        public async Task <IActionResult> Register(RegisterUserDTO userData)
        {
            if (ModelState.IsValid)
            {
                IEnumerable <IdentityError> errors = await registrationService.Register(userData);

                if (errors == null)
                {
                    var loginData = new LoginUserDTO {
                        UserName = userData.UserName, Password = userData.Password
                    };
                    string accessToken = await authenticationService.Authenticate(loginData);

                    if (string.IsNullOrEmpty(accessToken))
                    {
                        return(BadRequest("Invalid username or password"));
                    }
                    return(Ok(accessToken));
                }
                foreach (var error in errors)
                {
                    ModelState.AddModelError(error.Code, error.Description);
                }
            }
            return(Conflict(ModelState));
        }
Пример #28
0
        public IHttpActionResult PostRegisterUser(RegisterUserDTO newUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Request body is not in valid format."));
            }

            // If username or email exists new user can not be created
            // 1. Through DTOConverter

            // User user = DTOConverter.UserFromDTO(newUser);

            // usersService.CreateUser(Utilities.DTOConverter.UserDTO(newUser));
            // 2. Directly through Service
            try
            {
                User createdUser = usersService.CreateUser(newUser);

                return(CreatedAtRoute("PrivateUserEndpoint", new { id = createdUser.Id }, DTOConverter.PublicUserDTO(createdUser)));
            }
            catch (NameAlreadyExistsException e)
            {
                return(BadRequest(e.Message));
            }
            catch (EmailAlreadyExistsException e)
            {
                return(BadRequest(e.Message));
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
Пример #29
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterUserDTO model)
        {
            if (ModelState.IsValid) //The RegisterUserDTO Errormessage fires before
            {
                var mappedUser = _mapper.Map <EntityDentist>(model);
                mappedUser.Email = ($"{model.FirstName.Substring(0, 1)}{model.LastName}@qcdent.com").ToLower();

                try
                {
                    await _userServices.CheckIfEmailExistAsync(mappedUser.Email);
                }
                catch (AppException ex)
                {
                    return(BadRequest(new { message = ex.Message }));
                }

                try
                {
                    await _dentistServices.RegisterAsync(mappedUser);

                    return(Ok(model));
                }
                catch (AppException ex)
                {
                    return(BadRequest(new { message = ex.Message }));
                }
            }

            return(BadRequest(ModelState));
        }
Пример #30
0
        public async Task <ActionResult <UserDTO> > RegisterUser(RegisterUserDTO registerUserDTO)
        {
            if (await UserExists(registerUserDTO.Username))
            {
                return(BadRequest("Username is taken"));
            }

            using var hmac = new HMACSHA512();

            var user = new AppUser
            {
                Username     = registerUserDTO.Username.ToLower(),
                PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(registerUserDTO.Password)),
                PasswordSalt = hmac.Key
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return(new UserDTO
            {
                Username = user.Username,
                Token = _tokenService.CreateToken(user)
            });
        }