view auth/session.go @ 149:83d798ea9f58

Rename token.go to session.go because its more fitting.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Mon, 02 Jul 2018 11:14:46 +0200
parents auth/token.go@0c56c56a1c44
children 1585c334e8a7
line wrap: on
line source

package auth

import (
	"crypto/rand"
	"encoding/base64"
	"io"
	"time"
)

type Session struct {
	ExpiresAt int64    `json:"expires"`
	User      string   `json:"user"`
	Password  string   `json:"password"`
	Roles     []string `json:"roles"`
}

const (
	sessionKeyLength = 20
	maxTokenValid    = time.Hour * 3
)

func NewSession(user, password string, roles []string) *Session {

	// Create the Claims
	return &Session{
		ExpiresAt: time.Now().Add(maxTokenValid).Unix(),
		User:      user,
		Password:  password,
		Roles:     roles,
	}
}

func GenerateSessionKey() string {
	return base64.URLEncoding.EncodeToString(GenerateRandomKey(sessionKeyLength))
}

func GenerateRandomKey(length int) []byte {
	k := make([]byte, length)
	if _, err := io.ReadFull(rand.Reader, k); err != nil {
		return nil
	}
	return k
}

func GenerateSession(user, password string) (string, *Session, error) {
	roles, err := AllOtherRoles(user, password)
	if err != nil {
		return "", nil, err
	}
	token := GenerateSessionKey()
	session := NewSession(user, password, roles)
	ConnPool.Add(token, session)
	return token, session, nil
}