Beispiel #1
0
        public async Task <IActionResult> Register([FromBody] UserRegistrationRequestDto user)
        {
            if (ModelState.IsValid)
            {
                var existingUser = await _userManager.FindByEmailAsync(user.Email);

                if (existingUser != null)
                {
                    return(BadRequest(new RegistrationResponse()
                    {
                        Result = false,
                        Errors = new List <string>()
                        {
                            "Email already exist"
                        }
                    }));
                }

                var newUser = new IdentityUser()
                {
                    Email = user.Email, UserName = user.Email
                };
                var isCreated = await _userManager.CreateAsync(newUser, user.Password);

                if (isCreated.Succeeded)
                {
                    var jwtToken = newUser.GenerateJwtToken(_jwtConfig.Secret);

                    return(Ok(new RegistrationResponse()
                    {
                        Result = true,
                        Token = jwtToken
                    }));
                }

                return(new JsonResult(new RegistrationResponse()
                {
                    Result = false,
                    Errors = isCreated.Errors.Select(x => x.Description).ToList()
                }
                                      )
                {
                    StatusCode = 500
                });
            }

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