<commit_before>/*
 * Copyright (C) 2015 <NAME> <<EMAIL>>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package appcontext

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"strconv"
	"time"
)

// A TokenStore provides a temporary token to uniquely identify an user session.
type TokenStore struct {
	tstore       *TimedStore
	salt         string
	authDuration time.Duration
}

// NewTokenStore creates a new instance of TokenStore and defines a lifetime for
// unauthenticated and authenticated sessions and a salt for random input.
func NewTokenStore(noAuth, auth time.Duration, salt string) *TokenStore {
	ts := NewTimedStore(noAuth)
	return &TokenStore{
		tstore:       ts,
		salt:         salt,
		authDuration: auth,
	}
}

// Count gets the number of tokens stored by current instance.
func (s *TokenStore) Count() int {
	return s.Count()
}

// getInvalidTokenError gets the default error when an invalid or expired token
// is requested.
func (s *TokenStore) getInvalidTokenError(token string) error {
	return errors.New(fmt.Sprintf(
		"The requested token '%s' is invalid or is expired", token))
}

// GetValue gets the value stored by specified token.
func (s *TokenStore) GetValue(token string) (interface{}, error) {
	v, err := s.tstore.GetValue(token)
	if err != nil {
		return nil, s.getInvalidTokenError(token)
	}
	return v, err
}

// NewToken creates a new unique token and stores it into current TokenStore
// instance.
func (s *TokenStore) NewToken() string {
	hash := sha256.New()
	now := time.Now().Format(time.RFC3339Nano)

	// Tries to create unpredictable token
	// Most strength comes from 'rand.Read'
	// Another bits are used to avoid the chance of system random genarator
	//   is compromissed by internal issue
	hash.Write([]byte(now))
	hash.Write([]byte(strconv.Itoa(time.Now().Nanosecond())))
	hash.Write([]byte(s.salt))
	hash.Write(getRandomBytes(64 + time.Now().Second()))
	strSum := base64.URLEncoding.EncodeToString(hash.Sum(nil))

	s.tstore.AddValue(strSum, nil)
	return strSum
}

// RemoveToken removes specified token from current TokenStore instance.
func (s *TokenStore) RemoveToken(token string) error {
	err := s.tstore.RemoveValue(token)
	if err != nil {
		return s.getInvalidTokenError(token)
	}
	return nil
}

// SetTokenAsAuthenticated updates the lifetime of specified token to specified
// lifetime for authenticated sessions.
func (s *TokenStore) SetTokenAsAuthenticated(token string) error {
	err := s.tstore.SetValueDuration(token, s.authDuration)<commit_msg>Fixed salt implementation, was lacking randomness<commit_after>/*
 * Copyright (C) 2015 <NAME> <<EMAIL>>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package appcontext

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"strconv"
	"time"
)

// A TokenStore provides a temporary token to uniquely identify an user session.
type TokenStore struct {
	tstore       *TimedStore
	salt         string
	authDuration time.Duration
}

// NewTokenStore creates a new instance of TokenStore and defines a lifetime for
// unauthenticated and authenticated sessions and a salt for random input.
func NewTokenStore(noAuth, auth time.Duration, salt string) *TokenStore {
	ts := NewTimedStore(noAuth)
	return &TokenStore{
		tstore:       ts,
		salt:         salt,
		authDuration: auth,
	}
}

// Count gets the number of tokens stored by current instance.
func (s *TokenStore) Count() int {
	return s.Count()
}

// getInvalidTokenError gets the default error when an invalid or expired token
// is requested.
func (s *TokenStore) getInvalidTokenError(token string) error {
	return errors.New(fmt.Sprintf(
		"The requested token '%s' is invalid or is expired", token))
}

// GetValue gets the value stored by specified token.
func (s *TokenStore) GetValue(token string) (interface{}, error) {
	v, err := s.tstore.GetValue(token)
	if err != nil {
		return nil, s.getInvalidTokenError(token)
	}
	return v, err
}

// NewToken creates a new unique token and stores it into current TokenStore
// instance.
func (s *TokenStore) NewToken() string {
	hash := sha256.New()
	now := time.Now().Format(time.RFC3339Nano)

	// Tries to create unpredictable token
	// Most strength comes from 'rand.Read'
	// Another bits are used to avoid the chance of system random genarator
	//   is compromissed by internal issue
	hash.Write([]byte(now))
	hash.Write([]byte(strconv.Itoa(time.Now().Nanosecond())))
	hash.Write([]byte(s.salt))
	hash.Write(getRandomBytes(64 + time.Now().Second()))
	strSum := base64.URLEncoding.EncodeToString(hash.Sum(nil))
	s.salt = strSum

	s.tstore.AddValue(strSum, nil)
	return strSum
}

// RemoveToken removes specified token from current TokenStore instance.
func (s *TokenStore) RemoveToken(token string) error {
	err := s.tstore.RemoveValue(token)
	if err != nil {
		return s.getInvalidTokenError(token)
	}
	return nil
}

// SetTokenAsAuthenticated updates the lifetime of specified token to specified
// lifetime for authenticated sessions.
func (s *TokenStore) SetTokenAsAuthenticated(token string) error {
	err := s.tstore.SetValueDuration(token, s.authDuration)
{'fraction_non_alphanumeric': 0.09556893623591169, 'fraction_numerical': 0.010807472595337347, 'mean_word_length': 4.104806934594168, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1248028', 'n_tokens_mistral': 1979, 'n_tokens_neox': 1886, 'n_words': 744}