public AccountResponse LoginAccount(AccountLoginRequest request, Guid SessionID) { Sessions session = dbContext.Sessions .Where(s => s.SessionId.Equals(SessionID) && s.LastActivity < DateTime.Now.AddDays(1)) .FirstOrDefault(); if (session == null) { throw new BusinessLogicException(HttpStatusCode.BadRequest, ResponseCode.INVALID_LOGIN_SESSION.ToString()); } String passHash = PasswordHelper.ConvertToSHA512(request.Password); Users user = dbContext.Users .Where(u => u.Email.Equals(request.Email)) .FirstOrDefault(); if (user == null) { throw new BusinessLogicException(HttpStatusCode.BadRequest, ResponseCode.USER_NOT_EXIST.ToString()); } Users checkPass = dbContext.Users .Where(u => u.Email.Equals(request.Email) && u.PasswordHash.Equals(passHash)) .FirstOrDefault(); if (checkPass == null) { throw new BusinessLogicException(HttpStatusCode.BadRequest, ResponseCode.WRONG_COMBINATION_EMAIL_AND_PASSWORD.ToString()); } Genders gender = dbContext.Genders.Find(checkPass.GenderId); session.IsLogin = true; session.UserId = checkPass.UserId; session.LastActivity = DateTime.Now; using (IDbContextTransaction transaction = dbContext.Database.BeginTransaction()) { try { dbContext.Sessions.Update(session); dbContext.SaveChanges(); transaction.Commit(); } catch { transaction.Rollback(); throw new BusinessLogicException(HttpStatusCode.InternalServerError, ResponseCode.FAILED_TO_LOGIN.ToString()); } } return(ConstructResponse(checkPass, gender)); }
public SessionResponse CreateSession(string IpAddress, string userAgent) { Sessions session = dbContext.Sessions .Where(s => s.IpAddress.Equals(IpAddress) && s.UserAgent.Equals(userAgent) && s.LastActivity < DateTime.Now.AddDays(1)) .FirstOrDefault(); if (session != null) { if (session.IsLogin && session.UserId != null) { Users user = dbContext.Users.Find(session.UserId); UpdateLastActivity(session); return(constructResponse(session, user)); } UpdateLastActivity(session); return(constructResponse(session)); } using (IDbContextTransaction transaction = dbContext.Database.BeginTransaction()) { try { Sessions createdSession = new Sessions(); createdSession.SessionId = Guid.NewGuid(); createdSession.IpAddress = IpAddress; createdSession.IsLogin = false; createdSession.UserAgent = userAgent; createdSession.LastActivity = DateTime.Now; dbContext.Sessions.Add(createdSession); dbContext.SaveChanges(); transaction.Commit(); return(constructResponse(createdSession)); } catch { transaction.Rollback(); throw new BusinessLogicException(HttpStatusCode.InternalServerError, ResponseCode.FAILED_CREATED_SESSION.ToString()); } } }