public async Task <IHttpActionResult> Logout(LoggedInUserDTO userLogoutDto) { var validatedResponse = await AuthService.ValidateUserAndToken(); if (!validatedResponse.IsError) { LoggedInUserDTO loggedOutUserDTO = new LoggedInUserDTO() { UserLoggedOutDate = DateTime.Now.ToString(), ID = userLogoutDto.ID, Email = userLogoutDto.Email }; var response = AuthService.UserLoginDetailsUpdate(loggedOutUserDTO); if (!response.IsError) { return(Ok("Logged Out Successfully!")); } else { return(BadRequest("Logout Not Successful!")); } } else if (validatedResponse.TokenHasExpired) { return(BadRequest("Token Expired!")); } else { return(Unauthorized()); } }
/// <summary> /// Update The User Login Table When the User Logs out /// </summary> /// <param name="user"></param> /// <param name="location"></param> /// <returns></returns> public static async Task <CommonResponse> UserLoginDetailsUpdate(LoggedInUserDTO user, string location) { var response = new CommonResponse(); String SQL = "UPDATE User_Login " + "SET user_logged_out_date= GETDATE() WHERE Token = '" + user.Token + "' AND UserID = '" + user.ID + "'"; try { using (SqlConnection dbConn = new SqlConnection(selectConnection("main"))) { dbConn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = SQL; cmd.Connection = dbConn; await cmd.ExecuteNonQueryAsync(); dbConn.Close(); } } catch (Exception) { response.IsError = true; response.Message = "Error in Updating the Logout Details For User!"; } return(response); }
public static CommonResponse UserLoginDetailsUpdate(LoggedInUserDTO user) { var response = new CommonResponse(); String SQL = "UPDATE User_Login " + "SET UserLoggedOutDate= GETDATE() WHERE Token = '" + user.Token + "' AND UserID = '" + user.ID + "'"; try { using (SqlConnection dbConn = new SqlConnection(connectionString)) { dbConn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = SQL; cmd.Connection = dbConn; cmd.ExecuteNonQuery(); dbConn.Close(); } } catch (Exception) { response.IsError = true; response.Message = "Error in Updating the Logout Details For User!"; } return(response); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (User != null) _loggedInUser = User.Identity.GetIdentityLoggedInUserDto(); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (User != null) { _loggedInUser = User.Identity.GetIdentityLoggedInUserDto(); } }
public ViewModelNonGenericBase() { ModelState = new SimpleModelState(); KOMapping = new KOMapping(); HasDialog = false; HasAlerts = true; Title = ""; User = new LoggedInUserDTO(); DefaultSammyRoute = "list"; AllowEditing = true; }
/// <summary> /// Service Method To Login The User Login Information /// </summary> /// <param name="user"></param> /// <param name="location"></param> /// <returns></returns> public static async Task <CommonResponse> UserLoginDetailsAdded(LoggedInUserDTO user, string location) { var response = new CommonResponse(); String SQL = "INSERT INTO User_Login(userID," + "user_role," + "user_login_os," + "user_login_date," + "user_logged_in_timezone," + "user_logged_in_IP," + "user_logged_out_date," + "token)" + "VALUES('" + user.ID + "','" + user.RoleID + "','" + user.UserLoginOs + "', GETDATE() ,'" + user.UserLoggedInTimezone + "','" + user.UserLoggedInIP + "','" + user.UserLoggedOutDate + "','" + user.Token + "')"; try { using (SqlConnection dbConn = new SqlConnection(selectConnection("main"))) { dbConn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = SQL; cmd.Connection = dbConn; await cmd.ExecuteNonQueryAsync(); dbConn.Close(); } } catch (Exception ex) { response.IsError = true; response.Message = "Error in Registering User!"; ActionLogService.LogAction(new ActionLogModel() { UserID = user.UserID, ActionPerformed = "User Login Error : " + ex.Message, MethodName = "UserLoginDetailsAdded", IsError = true }, location); } return(response); }
public async Task <LoggedInUserDTO> LoginAsync(UserCredentialsDTO credentialsDTO) { string passwordHash = ConverterSuit.ByteArrayToHex(HashSuit.ComputeSha256(Encoding.UTF8.GetBytes(credentialsDTO.Password))); User user = await authRepository.LoginAsync(credentialsDTO.UserId, passwordHash); if (user == null) { return(null); } LoggedInUserDTO loggedInUser = mapper.Map <LoggedInUserDTO>(user); loggedInUser.JwtToken = jwtSuit.GetToken(user); return(loggedInUser); }
public static LoggedInUserDTO GetIdentityLoggedInUserDto(this IIdentity identity) { if (identity == null) return null; var user = new LoggedInUserDTO { Id = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.NameIdentifier), UserName = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Name), FirstName = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName), LastName = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Surname), Email = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Email) }; return user; }
public IHttpActionResult Post([FromUri] String userName, [FromUri] String password) { try { if (string.IsNullOrWhiteSpace(userName)) { return(Ok(ResponseHelper.CreateResponseDTOForException("UserName cannot be Balank"))); } else if (string.IsNullOrWhiteSpace(password)) { return(Ok(ResponseHelper.CreateResponseDTOForException("Password cannot be Balank"))); } else { LoggedInUserDTO loggedInUserDTO = _loginService.ValidateLoginAndCreateLoginSession(userName, password); if (loggedInUserDTO.LoginStatus) { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("PlatformSecretKey")); var signingCredientials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); string baseAddress = ConfigurationManager.AppSettings["BaseUri"].ToString(); var tokenOptions = new JwtSecurityToken( issuer: baseAddress, audience: baseAddress, claims: new List <Claim>(), expires: DateTimeHelper.GetISTDateTime().AddMinutes(6), signingCredentials: signingCredientials); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions); loggedInUserDTO.TokenString = tokenString; ResponseDTO responseDTO = new ResponseDTO(); responseDTO.Data = loggedInUserDTO; responseDTO.Status = true; responseDTO.Message = "Login Successful"; return(Ok(responseDTO)); } else { return(Ok(ResponseHelper.CreateResponseDTOForException("User Name or Password is InCorrect"))); } } } catch (PlatformModuleException ex) { //Write Log Here return(Ok(ResponseHelper.CreateResponseDTOForException(ex.Message))); } }
public static LoggedInUserDTO GetIdentityLoggedInUserDto(this IIdentity identity) { if (identity == null) { return(null); } var user = new LoggedInUserDTO { Id = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.NameIdentifier), UserName = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Name), FirstName = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName), LastName = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Surname), Email = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Email) }; return(user); }
public async Task <IHttpActionResult> Logout(LoggedInUserDTO userLogoutDto) { if (userLogoutDto == null) { return(BadRequest("Please provide valid inputs!")); } if (userLogoutDto.ID == 0) { return(BadRequest("Please provide valid user ID!")); } if (string.IsNullOrEmpty(userLogoutDto.Location)) { return(BadRequest("Please provide valid location!")); } if (await AuthService.ValidateUserAndToken(userLogoutDto.Token, userLogoutDto.ID, userLogoutDto.Email, userLogoutDto.Location)) { LoggedInUserDTO loggedOutUserDTO = new LoggedInUserDTO() { UserLoggedOutDate = DateTime.Now.ToString(), Token = userLogoutDto.Token, ID = userLogoutDto.ID, Email = userLogoutDto.Email }; var response = await AuthService.UserLoginDetailsUpdate(loggedOutUserDTO, userLogoutDto.Location); if (!response.IsError) { return(Ok("Logged Out Successfully!")); } else { return(BadRequest("Logout Not Successful!")); } } else { return(Unauthorized()); } }
public static LoggedInUserDTO ConvertToLoggedInUserDTO(VLC vLC) { LoggedInUserDTO loggedInUserDTO = new LoggedInUserDTO(); loggedInUserDTO.Id = vLC.VLCId; loggedInUserDTO.Code = vLC.VLCCode; loggedInUserDTO.Name = vLC.VLCName; loggedInUserDTO.EnrollmentDate = vLC.VLCEnrollmentDate; loggedInUserDTO.AgentName = vLC.AgentName; loggedInUserDTO.Contact = vLC.Contact; loggedInUserDTO.LoginStatus = true; loggedInUserDTO.Email = vLC.Email; loggedInUserDTO.Address = vLC.VLCAddress; loggedInUserDTO.Village = vLC.Village; loggedInUserDTO.City = vLC.City; loggedInUserDTO.State = vLC.VLCState; loggedInUserDTO.AgentAadhaar = vLC.VLCAgentAadhaar; return(loggedInUserDTO); }
public static CommonResponse UserLoginDetailsAdded(LoggedInUserDTO user) { var response = new CommonResponse(); String SQL = "INSERT INTO User_Login(userID," + "user_role," + "user_login_os," + "user_login_date," + "user_logged_in_timezone," + "user_logged_in_IP," + "user_logged_out_date," + "token)" + "VALUES('" + user.ID + "','" + user.RoleID + "','" + user.UserLoginOs + "', GETDATE() ,'" + user.UserLoggedInTimezone + "','" + user.UserLoggedInIP + "','" + user.UserLoggedOutDate + "','" + user.Token + "')"; try { using (SqlConnection dbConn = new SqlConnection(connectionString)) { dbConn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = SQL; cmd.Connection = dbConn; cmd.ExecuteNonQuery(); dbConn.Close(); } } catch (Exception ex) { response.IsError = true; response.Message = "Error in Registering User!"; } return(response); }
public LoggedInUserDTO ValidateLoginAndCreateLoginSession(string userName, string password) { LoggedInUserDTO loggedInUserDTO = new LoggedInUserDTO(); password = EncryptionHelper.Encryptword(password); // DC Check List <DistributionCenter> distributionCenters = unitOfWork.DistributionCenterRepository.GetAll(); if (distributionCenters.Where(v => v.Contact.Equals(userName, StringComparison.CurrentCultureIgnoreCase) && v.Password.Equals(password, StringComparison.CurrentCultureIgnoreCase)).Any()) { var dcEmployee = distributionCenters.Where(e => e.Contact.Equals(userName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (dcEmployee.IsDeleted.GetValueOrDefault()) { throw new PlatformModuleException("Your account is not active. Please Contact Administrator"); } loggedInUserDTO = LoggedInUserConvertor.ConvertToLoggedInDistributionCenterDTO(dcEmployee); loggedInUserDTO.LoginType = LoginType.DistributionCenter.ToString(); return(loggedInUserDTO); } //VLC Check List <VLC> vLCs = unitOfWork.VLCRepository.GetAll(); if (vLCs.Where(v => v.VLCName.Equals(userName, StringComparison.CurrentCultureIgnoreCase) && v.Password.Equals(password, StringComparison.CurrentCultureIgnoreCase)).Any()) { var vlcEmployee = vLCs.Where(e => e.VLCName.Equals(userName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); loggedInUserDTO = LoggedInUserConvertor.ConvertToLoggedInUserDTO(vlcEmployee); loggedInUserDTO.LoginType = LoginType.VLC.ToString(); return(loggedInUserDTO); } else { throw new PlatformModuleException("UserName and Password that you've entered doesn't match any account"); } }
public static LoggedInUserDTO ConvertToLoggedInDistributionCenterDTO(DistributionCenter distributionCenter) { LoggedInUserDTO loggedInUserDTO = new LoggedInUserDTO(); loggedInUserDTO.Id = distributionCenter.DCId; loggedInUserDTO.Code = distributionCenter.DCCode; loggedInUserDTO.Name = distributionCenter.DCName; loggedInUserDTO.EnrollmentDate = distributionCenter.DateOfRegistration; loggedInUserDTO.AgentName = distributionCenter.AgentName; loggedInUserDTO.Contact = distributionCenter.Contact; loggedInUserDTO.LoginStatus = true; loggedInUserDTO.Email = distributionCenter.Email; DCAddress dCAddress = distributionCenter.DCAddresses.Where(d => d.IsDefaultAddress).FirstOrDefault(); if (dCAddress != null) { loggedInUserDTO.Address = dCAddress.Address; loggedInUserDTO.Village = dCAddress.AddressTypeId.ToString(); loggedInUserDTO.City = dCAddress.City; loggedInUserDTO.State = dCAddress.State; } loggedInUserDTO.AgentAadhaar = distributionCenter.AADHAR; return(loggedInUserDTO); }
public async Task <IHttpActionResult> Login(User userForLoginDto) { if (userForLoginDto == null) { return(BadRequest("Please provide valid inputs!")); } if (string.IsNullOrEmpty(userForLoginDto.Email) || string.IsNullOrEmpty(userForLoginDto.Password)) { return(BadRequest("email or password values cannot be empty!")); } if (string.IsNullOrEmpty(userForLoginDto.Location)) { return(BadRequest("Please provide valid location!")); } var userFromRepo = await AuthService.Login(userForLoginDto.Email, userForLoginDto.Password, userForLoginDto.Location); if (userFromRepo == null) { return(Unauthorized()); } else { var claimsData = new[] { new Claim(ClaimTypes.NameIdentifier, userForLoginDto.ID.ToString()), new Claim(ClaimTypes.Name, userForLoginDto.Email), new Claim(ClaimTypes.Role, userFromRepo.RoleID.ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super secret key for creating the token")); var signingCreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claimsData), Expires = DateTime.Now.AddDays(1), SigningCredentials = signingCreds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); Ping ping = new Ping(); var replay = ping.Send(Dns.GetHostName()); IPAddress userIP = null; if (replay.Status == IPStatus.Success) { userIP = replay.Address; } OperatingSystem os_info = System.Environment.OSVersion; LoggedInUserDTO loggedInUser = new LoggedInUserDTO() { ID = userFromRepo.ID, Firstname = userFromRepo.Firstname, Lastname = userFromRepo.Lastname, Email = userFromRepo.Email, Gender = userFromRepo.Gender, RoleID = userFromRepo.RoleID, RegisteredDate = userFromRepo.RegisteredDate, Token = tokenHandler.WriteToken(token), UserLoggedInTimezone = TimeZone.CurrentTimeZone.ToString(), UserLoginDate = DateTime.Now.ToString(), UserLoggedInIP = userIP.ToString(), UserLoginOs = os_info.VersionString, }; CommonResponse response = await AuthService.UserLoginDetailsAdded(loggedInUser, userForLoginDto.Location); return(Ok(loggedInUser)); } }