Apex Check User Session Still Valid

Checking if a user has a valid session before making a query or call else an INVALID_SESSION error will be returned. The value of time remaining for the session can be cached and referenced so this query only runs a few times. Every time a user makes a request we can check the cache and see if the user has time remaining.

Query session information and returning UserSession model

public static UserSession getUserSessionInfo(User userObj){
      UserSession bpUserSession = new UserSession();
      List<AuthSession> session = [Select LastModifiedDate, NumSecondsValid from AuthSession where UsersId = : userObj.Id] ;

      for(AuthSession sessionObj : session){

      if (bpUserSession.getSecondsValid()!=null)

      if( bpUserSession.getSessionExpireTime() > System.now())

      List<AggregateResult> loginHistoryObj = [SELECT MAX(LoginTime) FROM LoginHistory WHERE UserId = : userObj.Id GROUP BY UserId];

      DateTime loginDateTime = (DateTime)loginHistoryObj[0].get('expr0');
      Date loginDate = loginDatetime.date();
      if( logindate != (DateTime.now()).date())

     return bpUserSession;

User Session model to set session information

    public class UserSession {
      DateTime lastModifiedDate;
      Integer secondsValid;
      DateTime sessionExpireTime;
      Boolean sessionValid;
      DateTime loginTime;

      public void setLastModifiedDate(DateTime lastModifiedDate){
        this.lastModifiedDate = lastModifiedDate;

      public DateTime getLastModifiedDate(){
        return lastModifiedDate;

      public void setSecondsValid(Integer secondsValid){
        this.secondsValid = secondsValid;

      public Integer getSecondsValid(){
        return secondsValid;

      public void setSessionExpireTime(DateTime sessionExpireTime){
        this.sessionExpireTime = sessionExpireTime;

      public DateTime getSessionExpireTime(){
        return sessionExpireTime;

      public void setSessionValid(Boolean sessionValid){
        this.sessionValid = sessionValid;

      public Boolean getSessionValid(){
        return sessionValid;

      public void setLoginTime(DateTime loginTime){
        this.loginTime = loginTime;

      public DateTime getLoginTime(){
        return loginTime;

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s