public async Task <IActionResult> Register([FromBody] UserRegistrationDTO userRegistrationDTO)
        {
            DBStatus status = await authService.RegisterAsync(userRegistrationDTO);

            ResponseStatusDTO responseStatusDTO = new ResponseStatusDTO((int)status, status.ToString());

            if (status == DBStatus.Failed)
            {
                return(BadRequest(new BadResponseDTO {
                    Status = (int)status, Errors = new Errors {
                        Message = new List <string> {
                            status.ToString()
                        }
                    }
                }));
            }
            else if (status == DBStatus.Taken)
            {
                return(BadRequest(new BadResponseDTO {
                    Status = (int)status, Errors = new Errors {
                        Message = new List <string> {
                            "User Id already taken"
                        }
                    }
                }));
            }
            return(Ok(responseStatusDTO));
        }
Esempio n. 2
0
        public async System.Threading.Tasks.Task SetUpAsync()
        {
            var userRegistrationDTO = new UserRegistrationDTO
            {
                PhoneNumber       = "9999999999",
                Password          = "******",
                CountryCode       = "91",
                FullName          = "test",
                DateOfBirth       = DateTime.UtcNow.AddYears(-25),
                Gender            = 1,
                Profession        = "test",
                School            = "test",
                LookingFor        = 1,
                MinAge            = 25,
                MaxAge            = 26,
                Distance          = 25,
                FunAndInteresting = "test",
                BucketList        = "test",
                Latitude          = 84.444454,
                Longitude         = -1.548454
            };
            var hashingServiceMock    = new Mock <IHashingService>();
            var userDomainServiceMock = new Mock <IUserDomainService>();

            userDomainServiceMock.Setup(x => x.SetUserInterests(It.IsAny <User>(), It.IsAny <int[]>())).ReturnsAsync(Result.Ok());
            var userFactory = new UserFactory(hashingServiceMock.Object, userDomainServiceMock.Object);
            var userResult  = await userFactory.CreateUserAsync(userRegistrationDTO);

            _user = userResult.Value;
        }
        public int UserRegistration(UserRegistrationDTO userRegistrationDTO)
        {
            try
            {
                SqlCommand cmd = this.StoredProcedureCommand("spAddUser");
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@email", userRegistrationDTO.email);
                cmd.Parameters.AddWithValue("@full_name", userRegistrationDTO.fullName);
                cmd.Parameters.AddWithValue("@password", EncodePasswordToBase64(userRegistrationDTO.password));
                cmd.Parameters.AddWithValue("@phone_no", userRegistrationDTO.phoneNumber);
                cmd.Parameters.Add("@user_id", SqlDbType.Int).Direction = ParameterDirection.Output;

                con.Open();
                cmd.ExecuteNonQuery();
                string id = cmd.Parameters["@user_id"].Value.ToString();
                con.Close();
                if (id != "")
                {
                    msmq.Send("Registration", "Registered Successfully", "*****@*****.**");
                    return(Convert.ToInt32(id));
                }
                return(-1);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                con.Close();
            }
        }
Esempio n. 4
0
        public async Task <IHttpActionResult> RegisterUser(UserRegistrationDTO newUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Add user to Db.
            try
            {
                Regex rx = new Regex(@"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
                if (rx.IsMatch(newUser.Email))                //valid email
                {
                    var user = Mapper.Map <User>(newUser);
                    user.TriviaCount = 499;                     //Default cache size is 500
                    db.Users.Add(user);
                    await db.SaveChangesAsync();

                    //Check Header for path to new resource
                    return(CreatedAtRoute(
                               "RegisterUser",
                               new { id = user.Id },
                               Mapper.Map <UserPublicDTO>(user)
                               ));
                }
                else
                {
                    throw new Exception("Invalid Email Id format");
                }
            }
            catch {
                return(BadRequest(String.Format("Account with email {0} already exists or invalid email", newUser.Email)));
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public async Task <List <UserRegistrationDTO> > GetAllUserRegistration()
        {
            List <UserRegistrationDTO> dt = new List <UserRegistrationDTO>();

            try
            {
                await _connection.OpenAsync();

                using (MySqlCommand cmd = new MySqlCommand("Get_AllUserRegistration", _connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    var dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        var row = new UserRegistrationDTO();
                        row.UserId    = Convert.ToInt32(dr["UserId"]);
                        row.Username  = dr["Username"].ToString();
                        row.FirstName = dr["FirstName"].ToString();
                        row.LastName  = dr["LastName"].ToString();

                        row.DateOfBirth   = Convert.ToDateTime(dr["DateOfBirth"]);
                        row.StartDate     = Convert.ToDateTime(dr["StartDate"]);
                        row.InstituteId   = Convert.ToInt32(dr["InstituteId"]);
                        row.InstituteName = dr["InstituteName"].ToString();
                        row.BranchName    = dr["BranchName"].ToString();
                        dt.Add(row);
                    }
                }
                return(dt);
            }
            catch { throw; }
            finally { await _connection.CloseAsync(); }
        }
Esempio n. 6
0
        public async Task <IActionResult> RegisterUser([FromBody] UserRegistrationDTO userRegistrationDTO)
        {
            if (userRegistrationDTO == null)
            {
                return(BadRequest(Constants.CommonErrorMessages.Request_Is_Not_Valid));
            }

            var userResult = await _userService.RegisterUserAsync(userRegistrationDTO);

            if (!userResult.IsSuccessed)
            {
                return(BadRequest(userResult.GetErrorString()));
            }

            var tokenResult = CreateUserToken(userResult.Value);

            if (!tokenResult.IsSuccessed)
            {
                return(BadRequest(tokenResult.GetErrorString()));
            }

            var response = new LoginResponseDTO
            {
                Token = tokenResult.Value.Value,
            };

            return(Ok(response));
        }
        public UserDTO InsertUserInformation(UserRegistrationDTO user)
        {
            var userRepository = new UserRepository();
            var userId         = userRepository.InsertUser(user);

            return(userRepository.GetUser(userId));
        }
        public async Task <ActionResult> Register(
            [FromBody] UserRegistrationDTO req)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(req));
            }

            //이메일로 회원 가입 여부 확인
            if (await _userManager.FindByEmailAsync(req.Email) != null)
            {
                return(BadRequest("The email is already in use."));
            }

            User user;

            try
            {
                user = await _accountService.Register(req);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok(new
            {
                Email = user.Email,
                Name = user.UserName
            }));
        }
Esempio n. 9
0
        public ActionResult Register(UserRegistrationDTO model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    bool success;
                    var  accountId = CustomerFacade.RegisterCustomer(model, out success);
                    if (success == false)
                    {
                        ModelState.AddModelError("Password", "Account with this email address already exists");
                        return(View("RegisterView", model));
                    }

                    SignInManager.SignIn(accountId, false);

                    return(RedirectToAction("Index", "Home"));
                }
                catch (ValidationException ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return(View("RegisterView", model));
        }
Esempio n. 10
0
        public IActionResult Register([FromBody] UserRegistrationDTO user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_userService.Get(u => u.UserName == user.UserName).Any())
            {
                return(BadRequest("User already exists."));
            }

            var registeredUser = _userService.CreateUser(user);

            if (registeredUser == null)
            {
                return(BadRequest("User registration failure."));
            }

            var identity = GetClaimsIdentity(registeredUser);

            //string token = JWTManager.GenerateToken(identity);
            var token = string.Empty;

            return(Created(registeredUser.Id.ToString(), token));
        }
Esempio n. 11
0
        public void Build_Should_Return_Success_User_Result_For_Valid_Inputs(UserRegistrationDTO userRegistrationDTO)
        {
            byte[] randomByteArray = GetRandomByteArray();
            var    result          = BuildUser(userRegistrationDTO, randomByteArray);

            result.IsSuccessed.Should().BeTrue();
            result.Value.Should().BeAssignableTo <User>();
            result.Value.PhoneNumber.PhoneNumber.Should().Be(userRegistrationDTO.PhoneNumber);
            result.Value.PhoneNumber.CountryCode.Should().Be(userRegistrationDTO.CountryCode);
            result.Value.Password.PasswordHash.Should().BeEquivalentTo(randomByteArray);
            result.Value.Password.PasswordSalt.Should().BeEquivalentTo(randomByteArray);
            result.Value.FullName.Should().Be(userRegistrationDTO.FullName);
            result.Value.Age.DateOfBirth.Should().Be(userRegistrationDTO.DateOfBirth);
            result.Value.Gender.GenderType.Should().Be((GenderType)userRegistrationDTO.Gender);
            result.Value.Profession.Should().Be(userRegistrationDTO.Profession);
            result.Value.School.Should().Be(userRegistrationDTO.School);
            result.Value.MatchPreference.LookingFor.GenderType.Should().Be(userRegistrationDTO.LookingFor);
            result.Value.MatchPreference.MinAge.Should().Be(userRegistrationDTO.MinAge);
            result.Value.MatchPreference.MaxAge.Should().Be(userRegistrationDTO.MaxAge);
            result.Value.MatchPreference.Distance.Should().Be(userRegistrationDTO.Distance);
            result.Value.FunAndInterestingThings.Should().Be(userRegistrationDTO.FunAndInteresting);
            result.Value.BucketList.Should().Be(userRegistrationDTO.BucketList);
            result.Value.Location.Latitude.Should().Be(userRegistrationDTO.Latitude);
            result.Value.Location.Longitude.Should().Be(userRegistrationDTO.Longitude);
        }
Esempio n. 12
0
        public HttpResponseMessage Post([FromBody] UserRegistrationDTO value)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
            try
            {
                var success = userService.Add(value);
                if (success)
                {
                    var okMessage = $"Succesfully created user: {value.Email}.";
                    tracer.Info(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, okMessage);
                    return(Request.CreateResponse(HttpStatusCode.OK, okMessage));
                }
            }
            catch (EntityException e)
            {
                tracer.Error(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, e);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
            const string message = "Incorrect request syntax.";

            tracer.Warn(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, message);
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
        }
Esempio n. 13
0
        private static Result <User> BuildUser(UserRegistrationDTO userRegistrationDTO, byte[] randomByteArray)
        {
            var hashingServiceMock = new Mock <IHashingService>();


            var ageResult = Age.Create(userRegistrationDTO.DateOfBirth);
            var lookingForGenderResult = Gender.Create(userRegistrationDTO.LookingFor);
            var matchPreference        = UserMatchPreference.Create(lookingForGenderResult.Value, userRegistrationDTO.MinAge, userRegistrationDTO.MaxAge, userRegistrationDTO.Distance);
            var phoneNumberResult      = UserPhoneNumber.Create(userRegistrationDTO.PhoneNumber, userRegistrationDTO.CountryCode);
            var genderResult           = Gender.Create(userRegistrationDTO.Gender);
            var loctionResult          = Location.Create(userRegistrationDTO.Latitude, userRegistrationDTO.Longitude);


            hashingServiceMock.Setup(x => x.GenerateSalt()).Returns(randomByteArray);
            hashingServiceMock.Setup(x => x.GetHash(userRegistrationDTO.Password, It.IsAny <byte[]>())).Returns(randomByteArray);
            var passwordSalt   = hashingServiceMock.Object.GenerateSalt();
            var passwordHash   = hashingServiceMock.Object.GetHash(userRegistrationDTO.Password, passwordSalt);
            var passwordResult = Password.Create(passwordHash, passwordSalt);

            var result = UserBuilder.Builder()
                         .WithName(userRegistrationDTO.FullName)
                         .WithPhoneNumber(phoneNumberResult.Value)
                         .WithPassword(passwordResult.Value)
                         .WithGender(genderResult.Value)
                         .WithMatchPreference(matchPreference.Value)
                         .WithAge(ageResult.Value)
                         .WithBucketList(userRegistrationDTO.BucketList)
                         .WithFunAndInterestingThings(userRegistrationDTO.FunAndInteresting)
                         .WithSchool(userRegistrationDTO.School)
                         .WithProfession(userRegistrationDTO.Profession)
                         .WithLocation(loctionResult.Value)
                         .Build();

            return(result);
        }
Esempio n. 14
0
        public async Task SetupAsync()
        {
            var hashAlgorithm         = new SHA256CryptoServiceProvider();
            var randomNumberGenerator = new RNGCryptoServiceProvider();
            var hashingService        = new Authentication.HashingService(randomNumberGenerator, hashAlgorithm);
            var userDomainServiceMock = new Mock <IUserDomainService>();

            userDomainServiceMock.Setup(x => x.SetUserInterests(It.IsAny <User>(), It.IsAny <int[]>())).ReturnsAsync(Result.Ok());
            var userFactory = new UserFactory(hashingService, userDomainServiceMock.Object);

            _userRegistrationDTO = new UserRegistrationDTO
            {
                PhoneNumber       = "9999999999",
                Password          = "******",
                CountryCode       = "91",
                FullName          = "test",
                DateOfBirth       = DateTime.UtcNow.AddYears(-25),
                Gender            = 1,
                Profession        = "test",
                School            = "test",
                LookingFor        = 1,
                MinAge            = 25,
                MaxAge            = 26,
                Distance          = 25,
                FunAndInteresting = "test",
                BucketList        = "test",
                Latitude          = 23.232433,
                Longitude         = -42.434345
            };
            var userResult = await userFactory.CreateUserAsync(_userRegistrationDTO);

            _user = userResult.Value;
        }
Esempio n. 15
0
        public bool Register(UserRegistrationDTO request, string Role)
        {
            if (userRepository.CheckEmailExists(request.Email.ToLower()))
            {
                return(false);
            }
            User u = new User
            {
                Email    = request.Email.ToLower(),
                Password = passwordManager.HashPassword(request.Password)
            };

            userRepository.Insert(u).Wait();
            rolesRepository.AssignRoleToUser(Role, u.Id);
            Customer customer = new Customer {
                Name = request.Name
            };

            if (Enum.TryParse(typeof(Districts), request.District, false, out object?district) && district != null)
            {
                customer.Residence = (Districts)district;
            }
            else
            {
                customer.Residence = Districts.Ryad;
            }

            customer.UserId = u.Id;
            customerRepository.Insert(customer);
            return(true);
        }
Esempio n. 16
0
        /// <summary>
        /// Adaugare utilizator
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        public int AddUser(UserRegistrationDTO userDTO)
        {
            if (string.IsNullOrWhiteSpace(userDTO.Username) || string.IsNullOrWhiteSpace(userDTO.Password) ||
                string.IsNullOrWhiteSpace(userDTO.Email))
            {
                throw new System.Exception("failed");
            }
            else
            {
                // Adauga un user
                MD5    md5        = new MD5CryptoServiceProvider();
                byte[] textToHash = Encoding.Default.GetBytes(userDTO.Password);
                byte[] result     = md5.ComputeHash(textToHash);
                string passHash   = BitConverter.ToString(result);

                User user = new User()
                {
                    Username = userDTO.Username,
                    Password = passHash,
                    Email    = userDTO.Email,
                    Role     = "user",
                    Verified = "no"
                };
                _dataAccess.UserRepository.Add(user);

                return(_dataAccess.UserRepository.FindFirstBy(u => u.Username.Equals(userDTO.Username)).UserID);
            }
        }
Esempio n. 17
0
        public async Task CreateUser(UserRegistrationDTO UserRegistrationDTO)
        {
            if (UserRegistrationDTO.Password == UserRegistrationDTO.ConfirmPassword)
            {
                User user = new User
                {
                    Email    = UserRegistrationDTO.Email,
                    UserName = UserRegistrationDTO.Email
                };
                var result = await _userManager.CreateAsync(user, UserRegistrationDTO.Password);

                if (result.Succeeded != true)
                {
                    string errors = "";
                    foreach (var error in result.Errors)
                    {
                        errors = errors + "<div class='alert alert-danger'>" + error.Description + "</div>";
                    }
                    throw new Exception(errors);
                }
            }
            else
            {
                throw new Exception("Пароли не совпадают");
            }
        }
Esempio n. 18
0
        public Guid RegisterUserAccount(UserRegistrationDTO userRegistration, bool createAdmin = false)
        {
            using (UnitOfWorkProvider.Create())
            {
                var userClaims = new List <Claim>();

                userClaims.Add(createAdmin
                    ? new Claim(ClaimTypes.Role, Claims.Admin)
                    : new Claim(ClaimTypes.Role, Claims.User));

                var account = coreService.CreateAccount(null, userRegistration.Password, userRegistration.Email,
                                                        null as Guid?,
                                                        null);

                Mapper.Map(userRegistration, account);

                foreach (var claim in userClaims)
                {
                    coreService.AddClaim(account.ID, claim.Type, claim.Value);
                }
                coreService.Update(account);

                return(account.ID);
            }
        }
Esempio n. 19
0
        public UserIdentityDTO CreateUser(UserRegistrationDTO user)
        {
            if (Repository.Get(u => u.UserName == user.UserName).Any())
            {
                return(null);
            }

            string passwordHash = CalculateMD5Hash(user.Password);

            Repository.Add(new User
            {
                FirstName      = user.FirstName,
                LastName       = user.LastName,
                Role           = "user",
                UserName       = user.UserName,
                HashedPassword = passwordHash
            });

            _unitOfWork.SaveChanges();

            User savedUser = Repository.Get(u => u.UserName == user.UserName).FirstOrDefault();

            if (savedUser == null)
            {
                return(null);
            }

            UserIdentityDTO identityDTO = new UserIdentityDTO();

            GetUserToUserIdentityDTOMapper().Map(savedUser, identityDTO);
            return(identityDTO);
        }
Esempio n. 20
0
        public async Task <Response <UserBasicDTO> > RegisterAsync(UserRegistrationDTO userRegistrationDTO)
        {
            try
            {
                User           user   = _mapper.Map <UserRegistrationDTO, User>(userRegistrationDTO);
                IdentityResult result = await _userManager.CreateAsync(user, userRegistrationDTO.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, RoleEnum.Member.GetName());

                    await _signInManager.SignInAsync(user, true, "Registration");

                    return(new Response <UserBasicDTO>(_mapper.Map <User, UserBasicDTO>(user)));
                }
                else
                {
                    string message = "";
                    foreach (var error in result.Errors)
                    {
                        message += error.Description + "|";
                    }
                    return(new Response <UserBasicDTO>(message));
                }
            }
            catch (Exception e)
            {
                return(new Response <UserBasicDTO>(e.Message));
            }
        }
Esempio n. 21
0
        public async Task <Result <User> > RegisterUserAsync(UserRegistrationDTO userRegistrationDTO)
        {
            var existingUserResult = await _userRepository.GetUserByPhoneNumber(userRegistrationDTO.PhoneNumber);

            if (existingUserResult.IsSuccessed)
            {
                return(Result.Fail <User>(UserErrorMessages.User_Already_Exists_With_Given_Phone_Number));
            }

            var userResult = await _userFactory.CreateUserAsync(userRegistrationDTO);

            if (!userResult.IsSuccessed)
            {
                return(Result.Fail <User>(userResult.GetErrorString()));
            }

            _userRepository.Create(userResult.Value);
            var saveResult = await _userRepository.SaveChangesAsync(Failed_To_Save_User);

            if (!saveResult.IsSuccessed)
            {
                return(Result.Fail <User>(saveResult.GetErrorString()));
            }

            _mediator.Publish(new UserCreated(userResult.Value));

            return(Result.Ok(userResult.Value));
        }
Esempio n. 22
0
        public async Task Create_Should_Return_Fail_Result_For_Invalid_Interests(UserRegistrationDTO userRegistrationDTO)
        {
            var errorMessage = "Error Message";

            byte[] randomByteArray = new byte[32];
            Random random          = new Random();

            random.NextBytes(randomByteArray);
            var hashingServiceMock = new Mock <IHashingService>();

            hashingServiceMock.Setup(x => x.GenerateSalt()).Returns(randomByteArray);
            hashingServiceMock.Setup(x => x.GetHash(userRegistrationDTO.Password, It.IsAny <byte[]>())).Returns(randomByteArray);
            List <Interest>     interests;
            List <UserInterest> userInterests;

            CreateInterestsAndUserInterests(out interests, out userInterests, userRegistrationDTO.InterestIds);
            var interestRepositoryMock = new Mock <IInterestRepository>();

            interestRepositoryMock.Setup(x => x.GetInterestsByIds(It.IsAny <int[]>())).ReturnsAsync(Result.Fail <IReadOnlyList <Interest> >(errorMessage));
            var userDomainService = new UserDomainService(interestRepositoryMock.Object);
            var userFactory       = new UserFactory(hashingServiceMock.Object, userDomainService);

            var userResult = await userFactory.CreateUserAsync(userRegistrationDTO);

            userResult.IsSuccessed.Should().BeFalse();
            userResult.GetErrorString().Should().Be(errorMessage);
        }
        /// <summary>
        /// Registers user (typically with default claims)
        /// </summary>
        /// <param name="userRegistration">User registration details</param>
        /// <param name="createAdmin">Grant user admin rights</param>
        /// <returns>ID of registered user</returns>
        public Guid RegisterUserAccount(UserRegistrationDTO userRegistration, bool createAdmin = false)
        {
            using (UnitOfWorkProvider.Create())
            {
                var userClaims = new List <Claim>();

                if (createAdmin)
                {
                    userClaims.Add(new Claim(ClaimTypes.Role, Claims.Admin));
                }
                else
                {
                    // for the moment there is just Player role left
                    userClaims.Add(new Claim(ClaimTypes.Role, Claims.Player));
                }
                var account = coreService.CreateAccount(userRegistration.UserName, userRegistration.Password, userRegistration.Email, null, null);


                AutoMapper.Mapper.Map(userRegistration, account);

                foreach (var claim in userClaims)
                {
                    coreService.AddClaim(account.ID, claim.Type, claim.Value);
                }

                coreService.Update(account);

                return(account.ID);
            }
        }
Esempio n. 24
0
        public void Build_Should_Return_Fail_User_Result_For_Invalid_FullName(UserRegistrationDTO userRegistrationDTO)
        {
            var result = BuildUser(userRegistrationDTO, GetRandomByteArray());

            result.IsSuccessed.Should().BeFalse();
            result.GetErrorString().Should().Be(UserBuilder.FullName_Is_Required);
        }
        public UserDetailDTO Register(UserRegistrationDTO userRegistration)
        {
            var user = _userMapper.ToUser(userRegistration);

            _context.User.Add(user);
            _context.SaveChanges();
            return(_userMapper.ToUserDetail(user));
        }
Esempio n. 26
0
 public IActionResult Register([FromBody] UserRegistrationDTO request)
 {
     if (accountLogic.Register(request, "User"))
     {
         return(Ok());
     }
     return(StatusCode(StatusCodes.Status409Conflict));
 }
Esempio n. 27
0
        public async Task <ActionResult> RegisterUser(UserRegistrationDTO model)
        {
            string msg = string.Empty;

            try
            {
                if (ModelState.IsValid)
                {
                    if (!string.IsNullOrEmpty(model.Id))
                    {
                        var user = UserManager.FindById(model.Id);
                        user.UserName    = model.Email;
                        user.Email       = model.Email;
                        user.ShipperDuns = model.ShipperDuns;

                        var result = await UserManager.UpdateAsync(user);

                        if (result.Succeeded)
                        {
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            msg = "Updated Data Successfully.";
                        }
                        else
                        {
                            msg = "Something went Wrong!!";
                        }
                    }
                    else
                    {
                        var user = new UPRD.Data.ApplicationUser {
                            UserName = model.Email, Email = model.Email, ShipperDuns = model.ShipperDuns, UserType = "C", IsEnabled = true
                        };
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            msg = "Registered User Successfully.";
                        }
                        else
                        {
                            msg = "Something went Wrong!!";
                        }
                    }
                }
                else
                {
                    msg = "Something went Wrong!!";
                }
            }
            catch (Exception ex)
            {
            }
            //var errors = ModelState.Values.SelectMany(v => v.Errors);
            return(Json(new { success = true, message = msg }, JsonRequestBehavior.AllowGet));
        }
        public async Task AddUser(UserRegistrationDTO model)
        {
            model.DynamicSalt = GenerateSalt.GetDinamicSalt();
            model.PassHash    = SHA256Encrypt.getHashSha256WithSalt(model.Password, model.DynamicSalt);
            var user = _mapper.Map <UserRegistrationDTO, User>(model);
            await _uow.UserRepos.AddUser(user);

            await CommitAsync();
        }
        public async Task <bool> RegisterUser(UserRegistrationDTO registerUserDTO)
        {
            var user = new IdentityUser <int> {
                UserName = registerUserDTO.Email, Email = registerUserDTO.Email
            };
            var result = await _userManager.CreateAsync(user, registerUserDTO.Password);

            return(result.Succeeded);
        }
Esempio n. 30
0
        public async Task <IActionResult> Register([FromBody] UserRegistrationDTO user)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await _userManager.FindByEmailAsync(user.Email);

                if (existingUser != null)
                {
                    return(BadRequest(new RegistrationResponseDTO()
                    {
                        Errors = new List <string>()
                        {
                            "Email already in use"
                        },
                        Success = false
                    }));
                }

                var newUser = new User()
                {
                    Email = user.Email, UserName = user.Username, Firstname = user.FirstName, Lastname = user.LastName
                };
                var isCreated = await _userManager.CreateAsync(newUser, user.Password);

                var createdUser = await _userManager.FindByEmailAsync(newUser.Email);

                var roleResult = await _userManager.AddToRoleAsync(createdUser, "User");

                if (isCreated.Succeeded)
                {
                    var jwtToken = GenerateJwtToken(newUser);
                    return(Ok(new RegistrationResponseDTO()
                    {
                        Success = true,
                        Token = jwtToken
                    }));
                }
                else
                {
                    return(BadRequest(new RegistrationResponseDTO()
                    {
                        Errors = isCreated.Errors.Select(t => t.Description).ToList(),
                        Success = false
                    }));
                }
            }

            return(BadRequest(new RegistrationResponseDTO()
            {
                Errors = new List <string>()
                {
                    "Invalid payload"
                },
                Success = false
            }));
        }