Ejemplo n.º 1
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                return(new BadRequestObjectResult(ErrorHelper.AddErrorToModelState("EmailAlreadyExist", "This email already exists!", ModelState)));
            }

            var applicationUser = new User
            {
                UserName       = model.UserName,
                Email          = model.Email,
                EmailConfirmed = true
            };

            var result = await _userManager.CreateAsync(applicationUser, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(ErrorHelper.AddErrorsToModelState(result, ModelState)));
            }

            return(new OkObjectResult("Account created"));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] RegistrationViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userIdentity = mapper.Map <User>(model);

            var result = await userManager.CreateAsync(userIdentity, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(ErrorHelper.AddErrorsToModelState(result, ModelState)));
            }

            var code = await userManager.GenerateEmailConfirmationTokenAsync(userIdentity);

            var    webRoot  = env.ContentRootPath;
            var    file     = System.IO.Path.Combine(webRoot, "Templates", "MailTemplate.html");
            string mailBody = System.IO.File.ReadAllText(file)
                              .Replace("{#user_id#}", userIdentity.Id.ToString())
                              .Replace("{#code#}", code.ToUrlSafeBase64());

            await emailService.SendEmailAsync(model.Email, "Подтвердите вашу учётную запись", mailBody);

            return(new OkObjectResult("Для завершения регистрации проверьте электронную почту и перейдите по ссылке, указанной в письме"));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] RegistrationViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userIdentity = _mapper.Map <AppUser>(model);

            var result = await _userManager.CreateAsync(userIdentity, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(ErrorHelper.AddErrorsToModelState(result, ModelState)));
            }

            await _appDbContext.Customers.AddAsync(new Customer { IdentityId = userIdentity.Id, Location = model.Location });

            await _appDbContext.SaveChangesAsync();

            return(new OkObjectResult("Account succesfully created!"));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var applicationUser = new ApplicationUser
            {
                UserName = model.UserName,
                Email    = model.Email
            };

            var result = await _userManager.CreateAsync(applicationUser, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(ErrorHelper.AddErrorsToModelState(result, ModelState)));
            }

            return(new OkObjectResult("Account created"));
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Authenticate([FromBody] FacebookAuthViewModel model)
        {
            // Generate an app access token
            var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);

            // Validate the user access token
            var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest(ErrorHelper.AddErrorToModelState("login_failure", "Invalid facebook token.", ModelState)));
            }

            // Request user data
            var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");

            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            // Upsert User
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var appUser = new AppUser
                {
                    Name       = userInfo.FirstName,
                    FamilyName = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture.Data.Url
                };

                var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(ErrorHelper.AddErrorsToModelState(result, ModelState)));
                }

                await _appDbContext.Customers.AddAsync(new Customer { IdentityId = appUser.Id, Location = "", Locale = userInfo.Locale, Gender = userInfo.Gender });

                await _appDbContext.SaveChangesAsync();
            }

            // Generate JWT
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser == null)
            {
                return(BadRequest(ErrorHelper.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)));
            }

            var jwt = await TokenGenerator.GenerateJwt(
                _jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id),
                _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(new OkObjectResult(jwt));
        }