working registration

This commit is contained in:
2023-03-28 23:00:18 +11:00
parent 8dc02a98bd
commit 7495a341cd
5 changed files with 498 additions and 9 deletions

View File

@@ -1,8 +1,10 @@
package models
import (
"errors"
"fmt"
"os"
"reflect"
"ccsecrets/utils"
@@ -30,7 +32,7 @@ const createUsers string = `
UserId INTEGER PRIMARY KEY ASC,
RoleId INTEGER,
UserName VARCHAR,
UserPass VARCHAR,
Password VARCHAR,
AccessToken varchar,
FOREIGN KEY (RoleId) REFERENCES roles(RoleId)
);
@@ -68,10 +70,12 @@ func ConnectDatabase() {
fmt.Printf("Connected to sqlite database file '%s'\n", sqlPath)
}
//sqlx.NameMapper = func(s string) string { return s }
// Make sure our tables exist
CreateTables()
defer db.Close()
//defer db.Close()
}
func CreateTables() {
@@ -82,11 +86,20 @@ func CreateTables() {
fmt.Printf("Error checking roles table : '%s'", err)
os.Exit(1)
}
if _, err = db.Exec("INSERT INTO roles VALUES(1, 'Admin', false, true);"); err != nil {
fmt.Printf("Error adding initial admin role : '%s'", err)
os.Exit(1)
}
// Users table
if _, err = db.Exec(createUsers); err != nil {
fmt.Printf("Error checking users table : '%s'", err)
os.Exit(1)
}
if _, err = db.Exec("INSERT INTO users VALUES(1, 1, 'Administrator', 'password', 'token');"); err != nil {
fmt.Printf("Error adding initial admin role : '%s'", err)
os.Exit(1)
}
// Secrets table
if _, err = db.Exec(createSecrets); err != nil {
fmt.Printf("Error checking secrets table : '%s'", err)
@@ -106,6 +119,52 @@ func CreateTables() {
}
}
// From https://stackoverflow.com/a/60100045
func GenerateInsertMethod(q interface{}) (string, error) {
if reflect.ValueOf(q).Kind() == reflect.Struct {
query := fmt.Sprintf("INSERT INTO %s", reflect.TypeOf(q).Name())
fieldNames := ""
fieldValues := ""
v := reflect.ValueOf(q)
for i := 0; i < v.NumField(); i++ {
if i == 0 {
fieldNames = fmt.Sprintf("%s%s", fieldNames, v.Type().Field(i).Name)
} else {
fieldNames = fmt.Sprintf("%s, %s", fieldNames, v.Type().Field(i).Name)
}
switch v.Field(i).Kind() {
case reflect.Int:
if i == 0 {
fieldValues = fmt.Sprintf("%s%d", fieldValues, v.Field(i).Int())
} else {
fieldValues = fmt.Sprintf("%s, %d", fieldValues, v.Field(i).Int())
}
case reflect.String:
if i == 0 {
fieldValues = fmt.Sprintf("%s\"%s\"", fieldValues, v.Field(i).String())
} else {
fieldValues = fmt.Sprintf("%s, \"%s\"", fieldValues, v.Field(i).String())
}
case reflect.Bool:
var boolSet int8
if v.Field(i).Bool() {
boolSet = 1
}
if i == 0 {
fieldValues = fmt.Sprintf("%s%d", fieldValues, boolSet)
} else {
fieldValues = fmt.Sprintf("%s, %d", fieldValues, boolSet)
}
default:
fmt.Printf("Unsupported type '%s'\n", v.Field(i).Kind())
}
}
query = fmt.Sprintf("%s(%s) VALUES (%s)", query, fieldNames, fieldValues)
return query, nil
}
return "", errors.New("SqlGenerationError")
}
func CheckColumnExists(table string, column string) (bool, error) {
var count int64
rows, err := db.Queryx("SELECT COUNT(*) AS CNTREC FROM pragma_table_info('" + table + "') WHERE name='" + column + "';")