diff --git a/main.go b/main.go index 172a819..25bff41 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "html/template" "log" "crypto/rand" + "encoding/json" "encoding/base32" "net/smtp" "strings" @@ -29,6 +30,12 @@ type config struct { TablePrefix string } +type UserData struct { + Username string `json:"username"` + UserPerms map[string]string `json:"perms"` + UserSettings map[string]string `json:"settings"` +} + var c config func Init(dbin *sqlx.DB, tp, sitename, fromaddr string) { @@ -43,6 +50,9 @@ func Init(dbin *sqlx.DB, tp, sitename, fromaddr string) { } func UsernameAvailable(username string) bool { + if len(username)==0 { + return false + } var u string q := fmt.Sprintf("select username from %s_auth where username=$1", c.TablePrefix) err := c.db.Get(&u, q, username) @@ -102,11 +112,43 @@ func Login(username, password string) bool { log.Println("Failed password for " + username) return false } - bump(username) + Bump(username) return true } -func bump(username string) { +func LoadUser(username string) (UserData, error) { + var u UserData + q:=fmt.Sprintf("select data from %s_userdata where username=$1", c.TablePrefix) + var d string + err:=c.db.Get(d, q, username) + if err != nil { + log.Println("Error loading user: " + err.Error()) + return u, err + } + err=json.Unmarshal([]byte(d), &u) + if err != nil { + log.Printf("Error decoding json on user %s. Unmarshal returned %s\n", err.Error()) + } + return u,err +} + +func SaveUser(username string, d UserData) bool { + q:=fmt.Sprintf("update %s_userdata set data=$1 where username=$2") + j, err:=json.Marshal(d) + if err != nil { + log.Printf("SaveUser: json.Marshal failed for username %s : %s\n", username, err.Error()) + return false + } + _, err=c.db.Exec(q, username, j) + if err != nil { + log.Printf("Saveuser: db.Exec failed for username %s : %s\n", username, err.Error()) + return false + } + return true + +} + +func Bump(username string) { q:=fmt.Sprintf("update %s_auth set lastseen=CURRENT_TIMESTAMP where username=$1", c.TablePrefix) _, err :=c.db.Exec(q, username) if err != nil { @@ -119,7 +161,7 @@ func RecoverByUsername(u string) { row:=c.db.QueryRow(q, u) err:=row.Scan(&username, &email) if err!=sql.ErrNoRows { - recoverycode:=randBytes(10) + recoverycode:=randBytes(16) qq:=fmt.Sprintf("update %s_auth set recoverycode=$1, recoverytime=NOW() where username=$2", c.TablePrefix) _,err:=c.db.Exec(qq, recoverycode, username) if err==nil { @@ -134,7 +176,7 @@ func RecoverByEmail(e string) { row:=c.db.QueryRow(q, e) err:=row.Scan(&username, &email) if err!=sql.ErrNoRows { - recoverycode:=randBytes(10) + recoverycode:=randBytes(16) qq:=fmt.Sprintf("update %s_auth set recoverycode=$1, recoverytime=NOW() where username=$2", c.TablePrefix) _,err:=c.db.Exec(qq, recoverycode, username) if err==nil {