public BaseController() {
   DBContext = new JolTudomEEntities();
   CustomIdentity id = User.Identity as CustomIdentity;
   if (id != null) {
     SM = new SessionManager(id.Token);
   }
 }
 public void DeleteSession() {
   using (JolTudomEEntities ent = new JolTudomEEntities()) {
     //ent.Attach(_Session);
     ent.Sessions.Remove(_Session);
     ent.Entry(_Session).State = System.Data.Entity.EntityState.Deleted;
     ent.SaveChanges();
   }
 }
 public void UpdateSessionLastAction() {
   using (JolTudomEEntities ent = new JolTudomEEntities()) {
     //ent.Attach(_Session);
     _Session.LastAction = DateTime.UtcNow;
     ent.Entry(_Session).State = System.Data.Entity.EntityState.Modified;
     ent.SaveChanges();
   }
 }
 private void GetSession() {
   using (JolTudomEEntities ent = new JolTudomEEntities()) {
     _Session = ent.Sessions.Include("Person").FirstOrDefault(s => s.Token == _Token);
     if (_Session == null) {
       throw new SessionNotAvailable();
     }
   }
 }
    public static SessionManager NewSession(int personid, int roleid) {
      // generate a token
      // this could be more secure ...
      byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
      byte[] key = Guid.NewGuid().ToByteArray();
      string token = Convert.ToBase64String(time.Concat(key).ToArray());

      using (JolTudomEEntities ent = new JolTudomEEntities()) {
        // delete those sessions, which are dead - over of the given timeout
        ent.usp_SessionsCleanup(JolTudomE_Api.Properties.Settings.Default.SessionTimeoutMinute);

        // delete those tests, which are not completed
        ent.usp_CleanupTests(JolTudomE_Api.Properties.Settings.Default.MaxTestExecutionHour);

        // this must be saved to the database with the timestamp
        ent.Sessions.Add(new Sessions { Token = token, PersonID = personid, RoleID = roleid, LastAction = DateTime.UtcNow });
        ent.SaveChanges();
      }

      SessionManager sm = new SessionManager(token);
      return sm;
    }
 private LoginResponse ValidateUser(string username, string password) {
   using (JolTudomEEntities db = new JolTudomEEntities()) {
     usp_Authenticate_Result result = db.usp_Authenticate(username, password).FirstOrDefault();
     if (result != null) {
       var session = SessionManager.NewSession(result.PersonID, result.RoleID).Session;
       _Token = session.Token;
       _UserName = session.Person.UserName;
       return new LoginResponse {
         PersonID = result.PersonID,
         RoleID = result.RoleID
       };
     }
     else
       return null;
   }
 }