Example #1
0
        public async Task RegisterAsync(UserModel user)
        {
            _validator.ValidateUser(user);
            var newUser = _mapper.Map <UserEntity>(user);
            var dbUser  = await _userManager.FindByNameAsync(user.UserName);

            if (dbUser is not null)
            {
                throw new CustomApiException(HttpStatusCode.Conflict, Constants.USERNAMETAKENERROR);
            }
            dbUser = await _userManager.FindByEmailAsync(user.Email);

            if (dbUser is not null)
            {
                throw new CustomApiException(HttpStatusCode.Conflict, Constants.EMAILTAKENERROR);
            }
            var result = await _userManager.CreateAsync(newUser, user.Password);

            if (!result.Succeeded)
            {
                throw new CustomApiException(HttpStatusCode.Conflict, Constants.FAILEDTOCREATEUSERERROR);
            }
            result = await _userManager.AddToRoleAsync(newUser, Enums.UserRolesType.Client.ToString());

            if (!result.Succeeded)
            {
                await _userManager.DeleteAsync(newUser);

                throw new CustomApiException(HttpStatusCode.Conflict, Constants.FAILEDTOCREATEUSERERROR);
            }
            string code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

            var uriBuilder = new UriBuilder
            {
                Scheme = _urlConfig.Scheme,
                Port   = _urlConfig.Port,
                Host   = _urlConfig.Host,
                Path   = Constants.CONFIRMEMAILPATH
            };
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query[Constants.USERIDKEY] = newUser.Id;
            query[Constants.CODEKEY]   = code;
            uriBuilder.Query           = query.ToString();
            string callbackUrl = uriBuilder.ToString();
            await _email.SendEmailAsync(new MailAddress(newUser.Email),
                                        Constants.DEFAULTEMAILCONFIRMATION,
                                        string.Format(Constants.DEFAULTEMAILCONFIRMATIONBODY, callbackUrl));
        }