github.com/jxgolibs/go-oauth2-server@v1.0.1/session/service.go (about)

     1  package session
     2  
     3  import (
     4  	"encoding/gob"
     5  	"errors"
     6  	"net/http"
     7  
     8  	"github.com/RichardKnop/go-oauth2-server/config"
     9  	"github.com/gorilla/sessions"
    10  )
    11  
    12  // Service wraps session functionality
    13  type Service struct {
    14  	sessionStore   sessions.Store
    15  	sessionOptions *sessions.Options
    16  	session        *sessions.Session
    17  	r              *http.Request
    18  	w              http.ResponseWriter
    19  }
    20  
    21  // UserSession has user data stored in a session after logging in
    22  type UserSession struct {
    23  	ClientID     string
    24  	Username     string
    25  	AccessToken  string
    26  	RefreshToken string
    27  }
    28  
    29  var (
    30  	// StorageSessionName ...
    31  	StorageSessionName = "go_oauth2_server_session"
    32  	// UserSessionKey ...
    33  	UserSessionKey = "go_oauth2_server_user"
    34  	// ErrSessonNotStarted ...
    35  	ErrSessonNotStarted = errors.New("Session not started")
    36  )
    37  
    38  func init() {
    39  	// Register a new datatype for storage in sessions
    40  	gob.Register(new(UserSession))
    41  }
    42  
    43  // NewService returns a new Service instance
    44  func NewService(cnf *config.Config, sessionStore sessions.Store) *Service {
    45  	return &Service{
    46  		// Session cookie storage
    47  		sessionStore: sessionStore,
    48  		// Session options
    49  		sessionOptions: &sessions.Options{
    50  			Path:     cnf.Session.Path,
    51  			MaxAge:   cnf.Session.MaxAge,
    52  			HttpOnly: cnf.Session.HTTPOnly,
    53  		},
    54  	}
    55  }
    56  
    57  // SetSessionService sets the request and responseWriter on the session service
    58  func (s *Service) SetSessionService(r *http.Request, w http.ResponseWriter) {
    59  	s.r = r
    60  	s.w = w
    61  }
    62  
    63  // StartSession starts a new session. This method must be called before other
    64  // public methods of this struct as it sets the internal session object
    65  func (s *Service) StartSession() error {
    66  	session, err := s.sessionStore.Get(s.r, StorageSessionName)
    67  	if err != nil {
    68  		return err
    69  	}
    70  	s.session = session
    71  	return nil
    72  }
    73  
    74  // GetUserSession returns the user session
    75  func (s *Service) GetUserSession() (*UserSession, error) {
    76  	// Make sure StartSession has been called
    77  	if s.session == nil {
    78  		return nil, ErrSessonNotStarted
    79  	}
    80  
    81  	// Retrieve our user session struct and type-assert it
    82  	userSession, ok := s.session.Values[UserSessionKey].(*UserSession)
    83  	if !ok {
    84  		return nil, errors.New("User session type assertion error")
    85  	}
    86  
    87  	return userSession, nil
    88  }
    89  
    90  // SetUserSession saves the user session
    91  func (s *Service) SetUserSession(userSession *UserSession) error {
    92  	// Make sure StartSession has been called
    93  	if s.session == nil {
    94  		return ErrSessonNotStarted
    95  	}
    96  
    97  	// Set a new user session
    98  	s.session.Values[UserSessionKey] = userSession
    99  	return s.session.Save(s.r, s.w)
   100  }
   101  
   102  // ClearUserSession deletes the user session
   103  func (s *Service) ClearUserSession() error {
   104  	// Make sure StartSession has been called
   105  	if s.session == nil {
   106  		return ErrSessonNotStarted
   107  	}
   108  
   109  	// Delete the user session
   110  	delete(s.session.Values, UserSessionKey)
   111  	return s.session.Save(s.r, s.w)
   112  }
   113  
   114  // SetFlashMessage sets a flash message,
   115  // useful for displaying an error after 302 redirection
   116  func (s *Service) SetFlashMessage(msg string) error {
   117  	// Make sure StartSession has been called
   118  	if s.session == nil {
   119  		return ErrSessonNotStarted
   120  	}
   121  
   122  	// Add the flash message
   123  	s.session.AddFlash(msg)
   124  	return s.session.Save(s.r, s.w)
   125  }
   126  
   127  // GetFlashMessage returns the first flash message
   128  func (s *Service) GetFlashMessage() (interface{}, error) {
   129  	// Make sure StartSession has been called
   130  	if s.session == nil {
   131  		return nil, ErrSessonNotStarted
   132  	}
   133  
   134  	// Get the last flash message from the stack
   135  	if flashes := s.session.Flashes(); len(flashes) > 0 {
   136  		// We need to save the session, otherwise the flash message won't be removed
   137  		s.session.Save(s.r, s.w)
   138  		return flashes[0], nil
   139  	}
   140  
   141  	// No flash messages in the stack
   142  	return nil, nil
   143  }
   144  
   145  // Close stops any running services
   146  func (s *Service) Close() {}