session.go (2022B)
1 // GoToSocial 2 // Copyright (C) GoToSocial Authors admin@gotosocial.org 3 // SPDX-License-Identifier: AGPL-3.0-or-later 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package bundb 19 20 import ( 21 "context" 22 "crypto/rand" 23 24 "github.com/superseriousbusiness/gotosocial/internal/db" 25 "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" 26 "github.com/superseriousbusiness/gotosocial/internal/id" 27 ) 28 29 type sessionDB struct { 30 conn *DBConn 31 } 32 33 func (s *sessionDB) GetSession(ctx context.Context) (*gtsmodel.RouterSession, db.Error) { 34 rss := make([]*gtsmodel.RouterSession, 0, 1) 35 36 // get the first router session in the db or... 37 if err := s.conn. 38 NewSelect(). 39 Model(&rss). 40 Limit(1). 41 Order("router_session.id DESC"). 42 Scan(ctx); err != nil { 43 return nil, s.conn.ProcessError(err) 44 } 45 46 // ... create a new one 47 if len(rss) == 0 { 48 return s.createSession(ctx) 49 } 50 51 return rss[0], nil 52 } 53 54 func (s *sessionDB) createSession(ctx context.Context) (*gtsmodel.RouterSession, db.Error) { 55 auth := make([]byte, 32) 56 crypt := make([]byte, 32) 57 58 if _, err := rand.Read(auth); err != nil { 59 return nil, err 60 } 61 if _, err := rand.Read(crypt); err != nil { 62 return nil, err 63 } 64 65 rs := >smodel.RouterSession{ 66 ID: id.NewULID(), 67 Auth: auth, 68 Crypt: crypt, 69 } 70 71 if _, err := s.conn. 72 NewInsert(). 73 Model(rs). 74 Exec(ctx); err != nil { 75 return nil, s.conn.ProcessError(err) 76 } 77 78 return rs, nil 79 }