creating auth codes in db

vilmibm 2023-10-24 06:22:21 +00:00
parent 5c6f4cce19
commit a3b13d21b3
4 changed files with 41 additions and 48 deletions

View File

@ -7,6 +7,7 @@ import (
"strconv"
"strings"
"git.tilde.town/tildetown/town/codes"
"git.tilde.town/tildetown/town/towndb"
"github.com/charmbracelet/lipgloss"
_ "github.com/mattn/go-sqlite3"
@ -162,11 +163,22 @@ func collectEmail(db *sql.DB, cs colorScheme, tty *tty.TTY) error {
return nil
}
fmt.Println("found a user so gonna email")
code := codes.NewCode(email)
fmt.Println(code)
ac := &towndb.AuthCode{
Code: code,
Email: email,
}
err = ac.Insert(db)
if err != nil {
// TODO log
return err
}
// TODO generate reset code
// TODO send email
// TODO report success
return nil
}

View File

@ -1,20 +1,16 @@
package invites
import (
"crypto/rand"
"database/sql"
"encoding/base64"
"errors"
"math/big"
"strings"
"time"
"git.tilde.town/tildetown/town/codes"
_ "github.com/mattn/go-sqlite3"
)
const (
dsn = "/town/var/invites/invites.db?mode=rw"
codeLen = 32
)
type Invite struct {
@ -33,7 +29,7 @@ func (i *Invite) Insert(db *sql.DB) error {
return err
}
i.Code = generateCode(i.Email)
i.Code = codes.NewCode(i.Email)
_, err = stmt.Exec(i.Code, i.Email)
if err != nil {
@ -53,44 +49,6 @@ func ConnectDB() (*sql.DB, error) {
return db, nil
}
func generateCode(email string) string {
charset := "abcdefghijklmnopqrztuvwxyz"
charset += strings.ToUpper(charset)
charset += "0123456789"
charset += "`~!@#$%^&*()-=_+[]{}|;:,./<>?"
code := []byte{}
max := big.NewInt(int64(len(charset)))
for len(code) < codeLen {
ix, err := rand.Int(rand.Reader, max)
if err != nil {
// TODO this is bad but I'm just kind of hoping it doesn't happen...often
panic(err)
}
code = append(code, charset[ix.Int64()])
}
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 Get(db *sql.DB, code string) (*Invite, error) {
inv := &Invite{
Code: code,

View File

@ -32,3 +32,11 @@ CREATE TABLE IF NOT EXISTS notes (
FOREIGN KEY (author) REFERENCES users(author)
);
CREATE TABLE IF NOT EXISTS auth_codes (
id INTEGER PRIMARY KEY,
created TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M', 'now', 'localtime')),
code TEXT,
email TEXT,
used INTEGER DEFAULT 0
);

View File

@ -173,3 +173,18 @@ func ConnectDB() (*sql.DB, error) {
return db, nil
}
type AuthCode struct {
ID int64
Code string
Email string
Used bool
Created time.Time
}
func (c *AuthCode) Insert(db *sql.DB) error {
// TODO
return nil
}
// TODO other auth code as needed