go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/auth/deprecated/memory_session.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package deprecated
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"sync"
    21  	"time"
    22  
    23  	"go.chromium.org/luci/common/clock"
    24  
    25  	"go.chromium.org/luci/server/auth"
    26  )
    27  
    28  // MemorySessionStore implement SessionStore.
    29  type MemorySessionStore struct {
    30  	lock    sync.Mutex
    31  	store   map[string]Session
    32  	counter int
    33  }
    34  
    35  // OpenSession create a new session for a user with given expiration time.
    36  // It returns unique session ID.
    37  func (s *MemorySessionStore) OpenSession(ctx context.Context, userID string, u *auth.User, exp time.Time) (string, error) {
    38  	s.lock.Lock()
    39  	defer s.lock.Unlock()
    40  	s.counter++
    41  	if s.store == nil {
    42  		s.store = make(map[string]Session, 1)
    43  	}
    44  	sid := fmt.Sprintf("%s/%d", userID, s.counter)
    45  	s.store[sid] = Session{
    46  		SessionID: sid,
    47  		UserID:    userID,
    48  		User:      *u,
    49  		Exp:       exp,
    50  	}
    51  	return sid, nil
    52  }
    53  
    54  // CloseSession closes a session given its ID. Does nothing if session is
    55  // already closed or doesn't exist. Returns only transient errors.
    56  func (s *MemorySessionStore) CloseSession(ctx context.Context, sessionID string) error {
    57  	s.lock.Lock()
    58  	defer s.lock.Unlock()
    59  	delete(s.store, sessionID)
    60  	return nil
    61  }
    62  
    63  // GetSession returns existing non-expired session given its ID. Returns nil
    64  // if session doesn't exist, closed or expired. Returns only transient errors.
    65  func (s *MemorySessionStore) GetSession(ctx context.Context, sessionID string) (*Session, error) {
    66  	s.lock.Lock()
    67  	defer s.lock.Unlock()
    68  	if session, ok := s.store[sessionID]; ok && clock.Now(ctx).Before(session.Exp) {
    69  		return &session, nil
    70  	}
    71  	return nil, nil
    72  }