view pkg/auth/connection.go @ 493:8a0737aa6ab6 metamorph-for-all

The connection pool is now only a session store.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Fri, 24 Aug 2018 14:25:05 +0200
parents b2dc9c2f69e0
children
line wrap: on
line source

package auth

import (
	"errors"
	"io"
	"sync"
	"time"

	"gemma.intevation.de/gemma/pkg/misc"
)

var ErrNoSuchToken = errors.New("No such token")

type Connection struct {
	session *Session

	access time.Time

	mu sync.Mutex
}

func (c *Connection) serialize(w io.Writer) error {
	if err := c.session.serialize(w); err != nil {
		return err
	}
	access, err := c.last().MarshalText()
	if err != nil {
		return err
	}
	wr := misc.BinWriter{w, nil}
	wr.WriteBin(uint32(len(access)))
	wr.WriteBin(access)
	return wr.Err
}

func (c *Connection) deserialize(r io.Reader) error {
	session := new(Session)
	if err := session.deserialize(r); err != nil {
		return err
	}

	rd := misc.BinReader{r, nil}
	var l uint32
	rd.ReadBin(&l)
	access := make([]byte, l)
	rd.ReadBin(access)

	if rd.Err != nil {
		return rd.Err
	}

	var t time.Time
	if err := t.UnmarshalText(access); err != nil {
		return err
	}

	*c = Connection{
		session: session,
		access:  t,
	}

	return nil
}

func (c *Connection) set(session *Session) {
	c.session = session
	c.touch()
}

func (c *Connection) touch() {
	c.mu.Lock()
	c.access = time.Now()
	c.mu.Unlock()
}

func (c *Connection) last() time.Time {
	c.mu.Lock()
	access := c.access
	c.mu.Unlock()
	return access
}