public async Task <IActionResult> Login([FromBody] Credentials credentials) { if (!ModelState.IsValid) { return(BadRequest(new { invalid = "Problem validation" })); } var result = await _signInManager .PasswordSignInAsync(credentials.Email, credentials.Password, false, false); if (!result.Succeeded) { return(BadRequest(new { invalid = "Не правильно введені дані!" })); } var user = await _userManager.FindByEmailAsync(credentials.Email); await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _jWTTokenService.CreateToken(user), refToken = _jWTTokenService.CreateRefreshToken(user) })); }
public async Task <IActionResult> RegisterTeacher([FromBody] TeacherRegisterVM model) { return(await HandleRequestAsync(async() => { string imageName = Path.GetRandomFileName() + ".jpg"; var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Uploaded\Users"); string pathSaveImages = InitStaticFiles .CreateImageByFileName(_env, _configuration, new string[] { Directory.GetCurrentDirectory(), @"wwwroot", "Uploaded", "Users" }, imageName, model.Photo); //+38 (098) 665 34 18 model.Photo = imageName; var rezult = await _teacherService.Create(model); if (rezult) { var user = _userManager.FindByEmailAsync(model.Email).Result; var teacher = await _teacherService.GetTeacherById(user.Id); JwtInfo jwtInfo; if (teacher != null) { // Return token jwtInfo = new JwtInfo() { Token = _jwtTokenService.CreateToken(user), RefreshToken = _jwtTokenService.CreateRefreshToken(user), SchoolId = teacher.SchoolId.ToString() }; } else { // Return token jwtInfo = new JwtInfo() { Token = _jwtTokenService.CreateToken(user), RefreshToken = _jwtTokenService.CreateRefreshToken(user), }; } this._logger.LogDebug("End method LoginUser..."); return Ok(jwtInfo); } else { var invalid = new Dictionary <string, string> { { "email", "Користувач з даною електронною поштою уже зареєстрований" } }; return BadRequest(invalid); } })); }
public async Task <IActionResult> Register([FromBody] UserRegisterDto model) { if (!ModelState.IsValid) { return(BadRequest("Wrong password or mail")); } var emailCheck = context.Users.FirstOrDefault(t => t.Email == model.Email); if (emailCheck != null) { return(BadRequest("Email already exists")); } var user = new User() { UserName = model.Email, Email = model.Email, Age = model.Age, LastName = model.LastName, Name = model.Name, RegisteredDate = DateTime.Now.ToShortDateString() }; IdentityResult result = await userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(BadRequest(CustomValidator.GetErrorsByIdentityResult(result))); } await userManager.AddToRoleAsync(user, "User"); context.SaveChanges(); var code = await userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action( "ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); EmailService emailService = new EmailService(); await emailService.SendEmail(model.Email, "Confirm your account", $"Confirm registration by clicking on the lin: <a href='{callbackUrl}'>link</a>"); return(Ok( new { token = jwtTokenService.CreateToken(user) })); }
public async Task <ActionResult <AppUserViewModel> > GetCurrentAppUserAsync() { var appUser = await _userManager.FindByClaimsPrincipal(HttpContext.User); return(new AppUserViewModel { Email = appUser.Email, Token = _jwtTokenService.CreateToken(appUser), DisplayName = appUser.DisplayName }); }
public async Task <IActionResult> Login([FromBody] LoginViewModel loginModel) { if (!ModelState.IsValid) { return(BadRequest(new { invalid = "Не валідна модель" })); } var result = await _signInManager .PasswordSignInAsync(loginModel.Email, loginModel.Password, false, false); if (!result.Succeeded) { return(BadRequest(new { invalid = "Не правильно введені дані!" })); } var user = await _userManager.FindByEmailAsync(loginModel.Email); await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _jwtTokenService.CreateToken(user) })); }
public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model) { var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result; var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { string path = _fileService.UploadAccountImage(userInfo.Picture); user = new DbUser { FirstName = userInfo.GivenName, LastName = userInfo.FamilyName, Email = userInfo.Email, UserName = userInfo.Email, SignUpTime = DateTime.Now, AvatarUrl = path }; var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword()); if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return(BadRequest(errors)); } var roleName = "User"; var roleresult = _roleManager.CreateAsync(new DbRole { Name = roleName }).Result; result = _userManager.AddToRoleAsync(user, roleName).Result; var invalid = new Dictionary <string, string> { { "googleInvalid", "Error google login." } }; if (!result.Succeeded) { return(BadRequest(invalid)); } } else { _fileService.UploadAccountImageIfNotExists(user, userInfo.Picture); } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _jWTTokenService.CreateToken(user), refToken = _jWTTokenService.CreateRefreshToken(user) })); }
public async Task <ResultDTO> Login([FromBody] UserLoginDTO model) { try { if (!ModelState.IsValid) { return(new ResultErrorDTO { Code = 405, Message = "ERROR!", Errors = CustomValidator.getErrorsByModelState(ModelState) }); } else { var result = _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false).Result; if (result.Succeeded) { var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, false); return(new ResultLoginDTO { Code = 200, Message = "OK!", Token = _IJWTTokenService.CreateToken(user) }); } else { return(new ResultErrorDTO { Code = 405, Message = "ERROR!", Errors = new List <string>() { "Incorrect email or password!" } }); } } } catch (Exception e) { return(new ResultErrorDTO { Code = 500, Message = "ERROR!", Errors = new List <string> { e.Message } }); } }
public async Task <IActionResult> LoginUser([FromBody] LoginDTO loginModel) { // Auto return errors from viewModel and other global errors return(await HandleRequestAsync(async() => { int countOfAttempts = this.HttpContext.Session.GetInt32("LoginAttemts") ?? 0; countOfAttempts++; this.HttpContext.Session.SetInt32("LoginAttemts", countOfAttempts); this._logger.LogDebug("Start method LoginUser..."); var result = await _signInManager.PasswordSignInAsync(loginModel.Email, loginModel.Password, false, false); if (!result.Succeeded) { return BadRequest(new InvalidData { Invalid = "Не правильно введені дані", ShowCaptcha = countOfAttempts > 4 ? true : false }); } var user = await _userManager.FindByEmailAsync(loginModel.Email); await _signInManager.SignInAsync(user, isPersistent: false); if (countOfAttempts > 4) { // TODO: Captcha validation this._recaptchaService.IsValid(loginModel.RecaptchaToken); } // Return token JwtInfo jwtInfo = new JwtInfo() { Token = _jwtTokenService.CreateToken(user), RefreshToken = _jwtTokenService.CreateRefreshToken(user) }; this.HttpContext.Session.SetInt32("LoginAttemts", 0); this._logger.LogDebug("End method LoginUser..."); return Ok(jwtInfo); })); }
public async Task <IActionResult> Login([FromBody] LoginViewModel model) { if (!ModelState.IsValid) { var errors = CustomValidator.GetErrorsByModel(ModelState); return(BadRequest(errors)); } var user = _context.Users.FirstOrDefault(u => u.Email == model.Email); if (user == null) { return(BadRequest(new { invalid = "Користувача із вказаними обліковими даними не знайдено" })); } var result = _signInManager .PasswordSignInAsync(user, model.Password, false, false).Result; if (!result.Succeeded) { return(BadRequest(new { invalid = "Користувача із вказаними обліковими даними не знайдено" })); } var block = _context.UserAccessLocks.FirstOrDefault(u => u.Id == user.Id); if (block != null) { return(BadRequest(new { invalid = "Нажаль Вас Заблоковано" })); } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _tokenService.CreateToken(user), refToken = _tokenService.CreateRefreshToken(user) })); }
public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model) { var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result; var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { string path = _fileService.UploadFacebookImage(userInfo.Picture); user = new DbUser { FirstName = userInfo.GivenName, LastName = userInfo.FamilyName, Email = userInfo.Email, UserName = userInfo.Email, SignUpTime = DateTime.Now, AvatarUrl = path }; var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword()); if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return(BadRequest(errors)); } var roleName = "User"; var roleresult = _roleManager.CreateAsync(new DbRole { Name = roleName }).Result; result = _userManager.AddToRoleAsync(user, roleName).Result; await _signInManager.SignInAsync(user, isPersistent : false); if (!result.Succeeded) { return(BadRequest(new { invalid = "We can't create user" })); } } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok(_jWTTokenService.CreateToken(_configuration, user, _userManager))); }
public async Task <ResultDTO> Login([FromBody] UserLoginDTO model) { if (!ModelState.IsValid) { return(new ResultErrorDTO { Status = 403, Message = "Invalid data for login", Errors = CustomValidator.GetErrorsByModel(ModelState) }); } //Переірка на успіх з логіном та паролем var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!result.Succeeded) { return(new ResultErrorDTO { Status = 401, Message = "Error", Errors = new List <string>() { "Incorrect login or password!" } }); } else { var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, false); return(new ResultLoginDTO { Status = 200, Message = "OK", Token = _jWTTokenService.CreateToken(user) }); } }
public async Task <ResultDto> Login([FromBody] UserLoginDto model) { if (!ModelState.IsValid) { return(new ResultErrorDto { Status = 400, Message = "ERROR", Errors = CustomValidator.GetErrorsByModel(ModelState) }); } else { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!result.Succeeded) { List <string> error = new List <string>(); error.Add("User is not found, password or email isn't correct!"); return(new ResultErrorDto { Status = 400, Message = "user not found!", Errors = error }); } else { var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, false); return(new ResultLoginDto { Status = 200, Message = "OK", Token = _jwtTokenService.CreateToken(user) }); } } }
public async Task <ResultDTO> Login([FromBody] UserLoginDTO model) { if (!ModelState.IsValid) { return(new ErrorResultDTO { StatusCode = 401, Message = "Login Error", Errors = CustomValidator.GetErrorByModel(ModelState) }); } // Перевірка на успіх логіну та паролю var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!result.Succeeded) { return(new ErrorResultDTO { StatusCode = 402, Message = "Login failed", Errors = new System.Collections.Generic.List <string> { "Login or password error" } }); } else { var user = await _userManager.FindByEmailAsync(model.Email); // вхід await _signInManager.SignInAsync(user, false); return(new SuccessResultDTO { StatusCode = 200, Message = "Ok", Token = _jwtTokenService.CreateToken(user) }); } }
public async Task <ResultDTO> Login([FromBody] UserLoginDTO model) { if (!ModelState.IsValid) { return(new ResultDTO { Status = 400, Message = "error", Errors = Validation.GetErrorsByModel(ModelState) }); } else { var result = await _signInManager.PasswordSignInAsync(model.email, model.password, false, false); if (!result.Succeeded) { List <string> error = new List <string>(); error.Add("User is not found? password or email isn`t correct!"); return(new ResultDTO { Status = 400, Message = "User is not found!" }); } else { var user = await _userManager.FindByEmailAsync(model.email); await _signInManager.SignInAsync(user, false); return(new ResultDTO { Status = 200, Message = "OK", Token = _jWTTokenService.CreateToken(user) }); } } }
public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model) { // 1.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); // 2. 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(new { invalid = "Invalid facebook token!" })); } // 3. we've got a valid token so we can request user data from fb 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); // 4. ready to create the local user account (if necessary) and jwt var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { string path = _fileService.UploadFacebookImage(userInfo.Picture.Data.Url); user = new DbUser { FirstName = userInfo.FirstName, LastName = userInfo.LastName, Email = userInfo.Email, UserName = userInfo.Email, SignUpTime = DateTime.Now, AvatarUrl = path }; var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword()); if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return(BadRequest(errors)); } var roleName = "User"; var roleresult = _roleManager.CreateAsync(new DbRole { Name = roleName }).Result; result = _userManager.AddToRoleAsync(user, roleName).Result; await _signInManager.SignInAsync(user, isPersistent : false); if (!result.Succeeded) { return(BadRequest(new { invalid = "We can't create user" })); } } else { user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { return(BadRequest(new { invalid = "Failed to create local user account." })); } } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok(_jWTTokenService.CreateToken(_configuration, user, _userManager))); }