~shulhan/karajo

36c17ca7459c0593afe9575f9e64fbf61f62d455 — Shulhan 1 year, 7 months ago de4d09f
all: implement session manager

The sessionManage manage creation of new session, getting the
existing session, and deleting the session.
2 files changed, 99 insertions(+), 0 deletions(-)

A session_manager.go
A session_manager_test.go
A session_manager.go => session_manager.go +52 -0
@@ 0,0 1,52 @@
// SPDX-FileCopyrightText: 2023 M. Shulhan <ms@kilabit.info>
// SPDX-License-Identifier: GPL-3.0-or-later

package karajo

import "github.com/shuLhan/share/lib/ascii"

// sessionManager manage the active session that map to authenticated user.
type sessionManager struct {
	value map[string]*User
}

// newSessionManager create new session manager.
func newSessionManager() (sm *sessionManager) {
	sm = &sessionManager{
		value: make(map[string]*User),
	}
	return sm
}

// new create new session for user u.
func (sm *sessionManager) new(u *User) (key string) {
	var (
		sessb []byte
		n     int
		ok    bool
	)
	for n < 5 {
		sessb = ascii.Random([]byte(ascii.LettersNumber), 32)
		key = string(sessb)
		_, ok = sm.value[key]
		if !ok {
			sm.value[key] = u
			return key
		}
		n++
	}
	// Failed to generate unique session, return empty key.
	return ``
}

// get the user related to session key.
// It will return nil if user is not exist.
func (sm *sessionManager) get(key string) (u *User) {
	u = sm.value[key]
	return u
}

// delete the session from storage.
func (sm *sessionManager) delete(key string) {
	delete(sm.value, key)
}

A session_manager_test.go => session_manager_test.go +47 -0
@@ 0,0 1,47 @@
// SPDX-FileCopyrightText: 2023 M. Shulhan <ms@kilabit.info>
// SPDX-License-Identifier: GPL-3.0-or-later

package karajo

import (
	"math/rand"
	"testing"

	"github.com/shuLhan/share/lib/test"
)

func TestSessionManager(t *testing.T) {
	rand.Seed(42)

	var (
		sm      = newSessionManager()
		expUser = &User{
			Name: `test`,
		}

		gotUser *User
		key     string
	)

	key = sm.new(expUser)
	gotUser = sm.get(key)

	test.Assert(t, `sessionManager.get: exist`, expUser, gotUser)

	sm.delete(key)

	var nilUser *User
	gotUser = sm.get(key)
	test.Assert(t, `sessionManager.get: not exist`, nilUser, gotUser)

	// Fill up the values to make it fail.

	sm.value[`FTiwaUT7G9GSS65BQQzOrW0BTgEPzZNA`] = expUser
	sm.value[`T3o4bnIGvsCe4lBrQJzFrXfxVhIrzHmc`] = expUser
	sm.value[`0FlaNsBlPcjJptPng4dCK6mPT1BTCjGJ`] = expUser
	sm.value[`BFrzrG0rzsl0eOI4G28wvNq9K3e1GW07`] = expUser
	sm.value[`ZwsldgKwLTudiA3O2FKgNadcJTHyJfAI`] = expUser

	key = sm.new(expUser)
	test.Assert(t, `sessionManager.new: failed`, ``, key)
}