Exemple #1
0
        public async Task <AuthResult> RegisterPersonWithJwtToken(PersonDTO person)
        {
            using (unitOfWork.BeginTransaction())
            {
                try
                {
                    ApplicationUser user = await unitOfWork.UserManager.FindByEmailAsync(person.Email);

                    if (user == null)
                    {
                        user = new ApplicationUser
                        {
                            Email = person.Email, UserName = person.UserName, PhoneNumber = person.PhoneNumber
                        };
                        var result = await unitOfWork.UserManager.CreateAsync(user, person.Password);

                        await unitOfWork.Save();

                        if (result.Succeeded)
                        {
                            var personMapped = PersonEntityToDtoMapper.Instance.MapBack(person);
                            personMapped.ApplicationUserFkId = user.Id;
                            unitOfWork.PersonRepository.Add(personMapped);
                            await unitOfWork.Save();

                            await unitOfWork.UserManager.AddToRoleAsync(user, "User");

                            unitOfWork.CommitTransaction();
                            return(await jwtSecurityService.GenerateJWTToken(user.Email));
                        }
                        else
                        {
                            //Як буть з не своїми помилками??
                            var apiResult = new AuthResult();
                            apiResult.GetErrors(result.Errors.Select(x => x.Description).ToList());
                            return(apiResult);
                        }
                    }

                    else
                    {
                        return(new AuthResult
                        {
                            Message = ErrorMessage.EmailIsAlreadyInUse.GetDescription(),
                            MessageType = nameof(ErrorMessage.EmailIsAlreadyInUse)
                        });
                    }
                }
                catch (Exception e)
                {
                    unitOfWork.RollbackTransaction();
                    logger.LogError(e.Message);
                    throw e;
                }
            }
        }