town/invites/invites.go

78 lines
1.3 KiB
Go
Raw Normal View History

2023-02-24 20:58:38 +00:00
package invites
import (
"database/sql"
2023-02-26 23:02:51 +00:00
"encoding/base64"
"math/rand"
"strings"
"time"
_ "github.com/mattn/go-sqlite3"
)
2023-02-26 23:02:51 +00:00
const (
dsn = "/town/var/invites/invites.db?mode=rw"
codeLen = 32
)
func ConnectDB() (*sql.DB, error) {
db, err := sql.Open("sqlite3", dsn)
if err != nil {
return nil, err
}
return db, nil
}
2023-02-26 23:02:51 +00:00
func generateCode(email string) string {
rand.Seed(time.Now().Unix())
charset := "abcdefghijklmnopqrztuvwxyz"
charset += strings.ToUpper(charset)
charset += "0123456789"
charset += "`~!@#$%^&*()-=_+[]{}|;:,./<>?"
code := []byte{}
for len(code) < codeLen {
code = append(code, charset[rand.Intn(len(charset))])
}
code = append(code, ' ')
eb := []byte(email)
for x := 0; x < len(eb); x++ {
code = append(code, eb[x])
}
return base64.StdEncoding.EncodeToString(code)
}
func Decode(code string) ([]string, error) {
decoded, err := base64.StdEncoding.DecodeString(code)
if err != nil {
return nil, err
}
return strings.Split(string(decoded), " "), nil
}
func InsertInvite(db *sql.DB, email string) error {
stmt, err := db.Prepare(`
INSERT INTO invites (code, email) VALUES (?, ?)
`)
if err != nil {
return err
}
_, err = stmt.Exec(generateCode(email), email)
if err != nil {
return err
}
defer stmt.Close()
return nil
}
// TODO decide on rest of API (eg Validate, Use, Get, etc)