github.com/decred/politeia@v1.4.0/politeiawww/session.go (about) 1 // Copyright (c) 2021-2022 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "net/http" 9 10 v3 "github.com/decred/politeia/politeiawww/api/http/v3" 11 plugin "github.com/decred/politeia/politeiawww/plugin/v1" 12 "github.com/gorilla/sessions" 13 ) 14 15 const ( 16 sessionValueUserID = "user-id" 17 sessionValueCreatedAt = "created-at" 18 ) 19 20 // extractSession extracts and returns the session from the http request 21 // cookie. 22 func (p *politeiawww) extractSession(r *http.Request) (*sessions.Session, error) { 23 return p.sessions.Get(r, v3.SessionCookieName) 24 } 25 26 // saveUserSession saves the encoded session values to the database and the 27 // encoded session ID to the response cookie if there were any changes to the 28 // session. The session is deleted from the database if the auth plugin has 29 // set the plugin session Delete field to true. 30 func (p *politeiawww) saveUserSession(r *http.Request, w http.ResponseWriter, s *sessions.Session, pluginSession *plugin.Session) error { 31 // Check if the session should be deleted. 32 if pluginSession.Delete { 33 s.Options.MaxAge = 0 34 return p.sessions.Save(r, w, s) 35 } 36 37 // Check if any values were updated. 38 var ( 39 userID = s.Values[sessionValueUserID].(string) 40 createdAt = s.Values[sessionValueUserID].(int64) 41 ) 42 if pluginSession.UserID == userID && 43 pluginSession.CreatedAt == createdAt { 44 // No changes were made. There is no 45 // need to update the database. 46 return nil 47 } 48 49 // Update the orignal session object with the changes 50 // made by the plugin. 51 s.Values[sessionValueUserID] = pluginSession.UserID 52 s.Values[sessionValueCreatedAt] = pluginSession.CreatedAt 53 54 // Save the changes to the database. 55 return p.sessions.Save(r, w, s) 56 } 57 58 func convertSession(s *sessions.Session) *plugin.Session { 59 // The interface{} values need to be type casted. 60 var ( 61 userID = s.Values[sessionValueUserID].(string) 62 createdAt = s.Values[sessionValueUserID].(int64) 63 ) 64 return &plugin.Session{ 65 UserID: userID, 66 CreatedAt: createdAt, 67 Delete: false, 68 } 69 }