public async Task <IActionResult> SignIn([FromBody] SignInRequestModel requestModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } SignInResponseModel responseModel = await _accountService.SignInAsync(requestModel); if (responseModel.IsRemoved) { ModelState.AddModelError(string.Empty, "That user has been banned"); return(BadRequest(ModelState)); } if (responseModel.SignInResult.Succeeded) { responseModel.SignInResult = null; return(Ok(responseModel)); } ModelState.AddModelError(string.Empty, "Wrong login or/and password"); return(BadRequest(ModelState)); }
public static SignInResponseModel TrySignIn(string userName, string password) { string result = string.Empty; using (var context = new AccountEntities()) { var responseMessage = new ObjectParameter("responseMessage", typeof(string)); context.appSignIn(userName, password, responseMessage); result = Convert.ToString(responseMessage.Value); } var response = new SignInResponseModel(); if (result.Equals(_responseSuccess)) { response.isSuccess = true; response.Message = _responseSuccess; } if (result.Equals(_responseIncorrectLogin)) { response.isSuccess = false; response.Message = _responseIncorrectLogin; } if (result.Equals(_responseIncorrectPassword)) { response.isSuccess = false; response.Message = _responseIncorrectPassword; } return(response); }
public async Task <SignInResponseModel> SignInAsync(SignInRequestModel requestModel) { SignInResponseModel responseModel = new SignInResponseModel(); responseModel.SignInResult = await _signInManager.PasswordSignInAsync(requestModel.Email, requestModel.Password, false, false); if (!responseModel.SignInResult.Succeeded) { return(responseModel); } ApplicationUser user = await _userManager.FindByEmailAsync(requestModel.Email); if (user.IsRemoved) { responseModel.IsRemoved = user.IsRemoved; return(responseModel); } string userRole = (await _userManager.GetRolesAsync(user)).FirstOrDefault(); responseModel.Id = user.Id; responseModel.FirstName = user.FirstName; responseModel.Token = _jwtHelper.GenerateAccessToken(user, userRole); return(responseModel); }
private async Task GenerateToken(HttpContext context) { var email = context.Request.Form["email"].ToString(); var password = context.Request.Form["password"].ToString(); var _accountService = (IAccountService)context.RequestServices.GetService(typeof(IAccountService)); //var _verifyService = (IVerificationService)context.RequestServices.GetService(typeof(IVerificationService)); //var _rawRabbitClient = (IBusClient)context.RequestServices.GetService(typeof(IBusClient)); var identity = await _accountService.CheckAsync(email, password); //response if account null or inactive if (identity == null || identity.Status == false) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 400; var code = Errors.INCORRECT_LOGIN; var message = Errors.INCORRECT_LOGIN_MSG; if (identity != null && identity.Status == false) { code = Errors.ACCOUNT_INACTIVE; message = Errors.ACCOUNT_INACTIVE_MSG; } await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Code = code, Message = message }, Formatting.Indented)); return; } var permissions = await _accountService.GetPermissionsOfAccountAsync(identity.Id); var now = DateTime.Now; var encodedJwt = TokenProviderMiddleware.GenerateAccessToken(_options, now, identity.Email, identity.Id.ToString(), permissions.ToArray()); var response = new SignInResponseModel { AccessToken = encodedJwt, Expires = now.AddSeconds((int)_options.Expiration.TotalSeconds), Account = identity.ToViewModel() }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
public SignInResponseModel SignIn([FromBody] SignInModel model) { SignInResponseModel responseModel = authService.SignIn(model); if (!responseModel.Error) { Response.Cookies.Append("session", responseModel.Session); } return(responseModel); }
public async Task <SignInResponseModel> FacebookLogin([FromBody] FacebookLoginModel model) { if (model == null || !ModelState.IsValid) { throw new CustomException(Errors.INVALID_REQUEST, Errors.INVALID_REQUEST_MSG); } var verifyResult = await this.VerifyFacebookAccessToken(model.AccessToken); if (verifyResult.IsValid) { var existAccount = await _accountService.FindByExternalProviderAsync("facebook", verifyResult.FacebookId); if (existAccount == null) { throw new CustomException(Errors.ACCOUNT_NOT_FOUND, Errors.ACCOUNT_NOT_FOUND_MSG); } else if (existAccount.Status == UserStatus.InActive) { throw new CustomException(Errors.ACCOUNT_INACTIVE, Errors.ACCOUNT_INACTIVE_MSG); } if (existAccount.AccountType == JobHop.Common.Enums.AccountType.Jobseeker && !existAccount.PhoneNumberVerified) { //return phone number in message for verify throw new CustomException(Errors.WAIT_FOR_VERIFICATION, existAccount.PhoneNumber); } var uname = string.IsNullOrEmpty(existAccount.UserName) ? $"Facebook:{verifyResult.FacebookId}" : existAccount.UserName; var permissions = await _accountService.GetPermissionsOfAccountAsync(existAccount.Id); var now = DateTime.UtcNow; var encodedJwt = TokenProviderMiddleware.GenerateAccessToken(_tokenOptions, now, uname, existAccount.Id.ToString(), permissions.ToArray()); var response = new SignInResponseModel { AccessToken = encodedJwt, Expires = now.AddSeconds((int)_tokenOptions.Expiration.TotalSeconds), Account = existAccount.ToViewModel() }; return(response); } else { throw new CustomException(Errors.INVALID_REQUEST, Errors.INVALID_REQUEST_MSG); } }
private async Task signIn(SignInResponseModel signInModel) { List <Claim> claims = new List <Claim> { new Claim(ClaimTypes.Role, signInModel.User.Role), new Claim(ClaimTypes.NameIdentifier, signInModel.User.Id.ToString()) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(60), IsPersistent = true, AllowRefresh = true }); }
public SignInResponseModel SignIn(SignInModel model) { SignInResponseModel responseModel = new SignInResponseModel(); using (DBConnection dbConnection = new DBConnection()) { try { SqlCommand command = new SqlCommand("SELECT * FROM Activation WHERE Activation = 1 AND User_Id IN " + "(SELECT User_Id FROM Users WHERE (Username = @Username OR Email = @Email) AND Password = @Password)", dbConnection.myConnection); command.Parameters.AddWithValue("@Username", model.Username); command.Parameters.AddWithValue("@Email", model.Username); command.Parameters.AddWithValue("@Password", CreateMD5(model.Password)); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { responseModel.Error = false; responseModel.Session = CreateMD5(model.Username + DateTime.UtcNow); command = new SqlCommand("INSERT INTO Sessions(User_Id, Session_Id, Date, Activity) VALUES(@User_Id, @Session_Id, @Date, 1)", dbConnection.myConnection); command.Parameters.AddWithValue("@User_Id", reader["User_Id"]); command.Parameters.AddWithValue("@Session_Id", responseModel.Session); command.Parameters.AddWithValue("@Date", DateTime.UtcNow); reader.Close(); command.ExecuteNonQuery(); } else { responseModel.ErrorMessage = "Неправильный логин или пароль"; } } } catch (Exception e) { Console.WriteLine(e.ToString()); responseModel.ErrorMessage = e.Message; } } return(responseModel); }
public async Task <SignInResponseModel> SigninUser(string email, string password) { var responseModel = new SignInResponseModel(); var user = await GetUserByEmail(email); if (user != null) { if (await _userManager.CheckPasswordAsync(user, password)) { try { responseModel.User = new BaseApplicationUserViewModel() { Id = user.Id, Role = user.UserRoles.First().Role.NormalizedName }; } catch (Exception e) { Log.Error(e, e.Message); responseModel.Login = LoginEnum.SignInError; return(responseModel); } responseModel.Login = LoginEnum.Successful; } else { responseModel.Login = LoginEnum.PasswordMismatch; } } else { responseModel.Login = LoginEnum.EmailNotFound; } return(responseModel); }
private async Task GenerateToken(HttpContext context) { var username = context.Request.Form["username"].ToString(); var password = context.Request.Form["password"].ToString(); var _accountService = (IAccountService)context.RequestServices.GetService(typeof(IAccountService)); var _verifyService = (IVerificationService)context.RequestServices.GetService(typeof(IVerificationService)); var _rawRabbitClient = (IBusClient)context.RequestServices.GetService(typeof(IBusClient)); //if username is not an email if (username != null && !username.Contains("@")) { //try to format username as internationlazition phone number try { //try to format with expectation that user filled country code username = PhoneNumberHelpers.GetFormatedPhoneNumber(username); } catch (NumberParseException) { //the username user provide is not an email or valid phone number context.Response.ContentType = "application/json"; context.Response.StatusCode = 400; await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Code = Errors.INCORRECT_LOGIN, Custom = Errors.INVALID_PHONE_NUMBER, Message = Errors.INCORRECT_LOGIN_MSG }, Formatting.Indented)); return; } } var identity = await _accountService.CheckAsync(username, password); //response if account null or inactive if (identity == null || identity.Status == UserStatus.InActive || (identity.AccountType == AccountType.Jobseeker && username.Contains("@"))) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 400; var code = Errors.INCORRECT_LOGIN; var message = Errors.INCORRECT_LOGIN_MSG; if (identity != null && identity.Status == UserStatus.InActive) { code = Errors.ACCOUNT_INACTIVE; message = Errors.ACCOUNT_INACTIVE_MSG; } await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Code = code, Message = message }, Formatting.Indented)); return; } if (identity.AccountType == AccountType.Jobseeker && !identity.PhoneNumberVerified) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 400; //1 account has only 1 verification => get first var verification = (await _verifyService.GetVerificationsOfAccount(identity.Id)).FirstOrDefault(); //account is locked because exceeded limit of retried or resend times if (verification.Retry >= VerificationService.MAX_RETRY || verification.Resend > VerificationService.MAX_RESEND) { await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Code = Errors.VERIFICATION_LOCKED, Message = Errors.VERIFICATION_LOCKED_MSG }, Formatting.Indented)); } else //wait for verification { await context.Response.WriteAsync(JsonConvert.SerializeObject(new { Code = Errors.WAIT_FOR_VERIFICATION, Message = Errors.WAIT_FOR_VERIFICATION_MSG }, Formatting.Indented)); } return; } //add banana reward for first login in day if (identity.AccountType == AccountType.Jobseeker) { var tracker = await _accountService.AddTracker(new LoginTracker { Account = identity, LoginAt = DateTime.Now }); if (tracker != null) { await _rawRabbitClient.PublishAsync(new AccountLoggedIn { AccountId = identity.Id, LoginAt = tracker.LoginAt }); } } var permissions = await _accountService.GetPermissionsOfAccountAsync(identity.Id); var now = DateTime.Now; var encodedJwt = TokenProviderMiddleware.GenerateAccessToken(_options, now, identity.UserName, identity.Id.ToString(), permissions.ToArray()); var response = new SignInResponseModel { AccessToken = encodedJwt, Expires = now.AddSeconds((int)_options.Expiration.TotalSeconds), Account = identity.ToViewModel() }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }