auth.go

 1package backend
 2
 3import (
 4	"crypto/rand"
 5	"encoding/hex"
 6
 7	"github.com/charmbracelet/log"
 8	"golang.org/x/crypto/bcrypt"
 9)
10
11const saltySalt = "salty-soft-serve"
12
13// HashPassword hashes the password using bcrypt.
14func HashPassword(password string) (string, error) {
15	crypt, err := bcrypt.GenerateFromPassword([]byte(password+saltySalt), bcrypt.DefaultCost)
16	if err != nil {
17		return "", err
18	}
19
20	return string(crypt), nil
21}
22
23// VerifyPassword verifies the password against the hash.
24func VerifyPassword(password, hash string) bool {
25	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password+saltySalt))
26	return err == nil
27}
28
29// GenerateAccessToken returns a random unique token.
30func GenerateAccessToken() string {
31	buf := make([]byte, 20)
32	if _, err := rand.Read(buf); err != nil {
33		log.Error("unable to generate access token")
34		return ""
35	}
36
37	return "ss_" + hex.EncodeToString(buf)
38}