scsusers/meta.go

89 lines
1.8 KiB
Go
Raw Normal View History

2023-09-26 20:45:19 +00:00
package scsusers
import (
2023-10-07 13:48:40 +00:00
"database/sql"
2023-09-26 20:45:19 +00:00
"fmt"
"log"
"net/mail"
2023-09-26 20:45:19 +00:00
)
type Metadata struct {
MetaKey string `db:"meta_key"`
MetaValue string `db:"meta_value"`
}
func (u *UserData) GetEmail() (string, bool) {
_, err := mail.ParseAddress(u.Username)
if err == nil {
return u.Username, true
}
e, ok := u.Get("email")
if !ok {
return "", false
}
_, err = mail.ParseAddress(e)
if err != nil {
return "", false
}
return e, true
}
2023-10-07 13:48:40 +00:00
func (u *UserData) LoadMeta() bool {
2023-10-07 14:20:01 +00:00
q := fmt.Sprintf("select meta_key, meta_value, id from %s_meta where user=?", c.TablePrefix)
2023-10-07 13:48:40 +00:00
rows, err := c.db.Query(q, u.UserID)
if err != nil && err != sql.ErrNoRows {
log.Printf("scsuser.Get: select: %s", err.Error())
return false
}
for rows.Next() {
var m metadata
2023-10-07 13:50:11 +00:00
rows.Scan(&m.Key, &m.Value, &m.ID)
2023-10-07 13:48:40 +00:00
u.Meta[m.Key] = m
}
return true
}
2023-09-26 20:45:19 +00:00
func (u *UserData) Get(key string) (string, bool) {
tmp, ok := u.Meta[key]
return tmp.Value, ok
}
func (u *UserData) Delete(key string) {
tmp, ok := u.Meta[key]
if ok {
_, err := c.db.Query(fmt.Sprintf("delete from %s_meta where id=?", c.TablePrefix), tmp.ID)
if err != nil {
log.Printf("scsauth: set: delete: %s", err.Error())
}
2023-10-06 23:06:54 +00:00
delete(u.Meta, key)
2023-09-26 20:45:19 +00:00
}
}
func (u *UserData) Set(key, value string) error {
tmp, ok := u.Meta[key]
if ok {
_, err := c.db.Query(fmt.Sprintf("delete from %s_meta where id=?", c.TablePrefix), tmp.ID)
if err != nil {
log.Printf("scsauth: set: delete: %s", err.Error())
return err
}
}
var insertid int64
2023-10-06 23:41:11 +00:00
err := c.db.Get(&insertid, fmt.Sprintf("insert into %s_meta (user, meta_key, meta_value) VALUES (?,?,?) returning id", c.TablePrefix), u.UserID, key, value)
2023-09-26 20:45:19 +00:00
if err != nil {
log.Printf("scsauth: set: insert: %s", err.Error())
return err
}
var m metadata
m.Key = key
m.Value = value
m.ID = insertid
u.Meta[key] = m
2023-10-07 13:41:57 +00:00
log.Printf("%#v", u)
2023-09-26 20:45:19 +00:00
return nil
}