summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2020-03-27 18:32:10 +0530
committerAndinus <andinus@nand.sh>2020-03-27 18:32:10 +0530
commit97f36a08c7a5e3bd7921a26af89eee8ad9b3e3d7 (patch)
tree3c1da88b84708ed2935f680ac60f235feae5e803
parent73952003142c7106482a198ce6024cba00c35e44 (diff)
downloadperseus-97f36a08c7a5e3bd7921a26af89eee8ad9b3e3d7.tar.gz
Add AddUser func
-rw-r--r--auth/register.go36
-rw-r--r--user/adduser.go42
2 files changed, 43 insertions, 35 deletions
diff --git a/auth/register.go b/auth/register.go
index 086d3ce..69e05ad 100644
--- a/auth/register.go
+++ b/auth/register.go
@@ -3,7 +3,6 @@ package auth
 import (
 	"log"
 	"strings"
-	"time"
 
 	"tildegit.org/andinus/perseus/storage/sqlite3"
 	"tildegit.org/andinus/perseus/user"
@@ -25,39 +24,6 @@ func Register(db *sqlite3.DB, regInfo map[string]string) error {
 	}
 	u.SetPassword(pass)
 
-	// Acquire write lock on the database.
-	db.Mu.Lock()
-	defer db.Mu.Unlock()
-
-	err = insertRegRecords(db, u)
-	return err
-}
-
-func insertRegRecords(db *sqlite3.DB, u user.User) error {
-	// Start the transaction
-	tx, err := db.Conn.Begin()
-	if err != nil {
-		log.Printf("auth/register.go: %s\n",
-			"Failed to begin transaction")
-		return err
-	}
-
-	usrStmt, err := db.Conn.Prepare(`
-INSERT INTO users(id, username, password, regTime) values(?, ?, ?, ?)`)
-	if err != nil {
-		log.Printf("auth/register.go: %s\n",
-			"Failed to prepare statement")
-		return err
-	}
-	defer usrStmt.Close()
-
-	_, err = usrStmt.Exec(u.ID(), u.Username(), u.Password(), time.Now().UTC())
-	if err != nil {
-		log.Printf("auth/register.go: %s\n",
-			"Failed to execute statement")
-		return err
-	}
-
-	tx.Commit()
+	err = u.AddUser(db)
 	return err
 }
diff --git a/user/adduser.go b/user/adduser.go
new file mode 100644
index 0000000..873454b
--- /dev/null
+++ b/user/adduser.go
@@ -0,0 +1,42 @@
+package user
+
+import (
+	"log"
+	"time"
+
+	"tildegit.org/andinus/perseus/storage/sqlite3"
+)
+
+// AddUser adds the user to record.
+func (u *User) AddUser(db *sqlite3.DB) error {
+	// Acquire write lock on the database.
+	db.Mu.Lock()
+	defer db.Mu.Unlock()
+
+	// Start the transaction
+	tx, err := db.Conn.Begin()
+	if err != nil {
+		log.Printf("user/adduser.go: %s\n",
+			"failed to begin transaction")
+		return err
+	}
+
+	usrStmt, err := db.Conn.Prepare(`
+INSERT INTO users(id, username, password, regTime) values(?, ?, ?, ?)`)
+	if err != nil {
+		log.Printf("user/adduser.go: %s\n",
+			"failed to prepare statement")
+		return err
+	}
+	defer usrStmt.Close()
+
+	_, err = usrStmt.Exec(u.id, u.username, u.password, time.Now().UTC())
+	if err != nil {
+		log.Printf("user/adduser.go: %s\n",
+			"failed to execute statement")
+		return err
+	}
+
+	tx.Commit()
+	return err
+}