summary refs log tree commit diff stats
path: root/account/login.go
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2020-03-29 16:10:59 +0530
committerAndinus <andinus@nand.sh>2020-03-29 16:10:59 +0530
commita6826055bf4e6a23f80da047ccfe4509a209f3a6 (patch)
treef2bb2bec35ee5e61cb42f4edffb04368a0f8ba60 /account/login.go
parent7b95d6b80dd2d1efb26f7c515383abd4f0dc9d42 (diff)
downloadperseus-a6826055bf4e6a23f80da047ccfe4509a209f3a6.tar.gz
Initial perseus rewrite
Diffstat (limited to 'account/login.go')
-rw-r--r--account/login.go50
1 files changed, 50 insertions, 0 deletions
diff --git a/account/login.go b/account/login.go
new file mode 100644
index 0000000..c81fcbd
--- /dev/null
+++ b/account/login.go
@@ -0,0 +1,50 @@
+package account
+
+import (
+	"log"
+
+	"tildegit.org/andinus/perseus/password"
+	"tildegit.org/andinus/perseus/storage"
+)
+
+// Login takes in login details and returns an error. If error doesn't
+// equal nil then consider login failed. It will also set the u.Token
+// field.
+func (u *User) Login(db *storage.DB) error {
+	// Acquire read lock on the database.
+	db.Mu.RLock()
+
+	// Get password for this user from the database.
+	stmt, err := db.Conn.Prepare("SELECT hash FROM accounts WHERE username = ?")
+	if err != nil {
+		log.Printf("account/login.go: %s\n",
+			"failed to prepare statement")
+		return err
+	}
+	defer stmt.Close()
+
+	var hash string
+	err = stmt.QueryRow(u.Username).Scan(&hash)
+	if err != nil {
+		log.Printf("account/login.go: %s\n",
+			"query failed")
+		return err
+	}
+	u.Hash = hash
+
+	// Check user's password.
+	err = password.Check(u.Password, u.Hash)
+	if err != nil {
+		log.Printf("account/login.go: %s%s\n",
+			"user login failed, username: ", u.Username)
+		return err
+	}
+	db.Mu.RUnlock()
+
+	err = u.addToken(db)
+	if err != nil {
+		log.Printf("account/login.go: %s\n",
+			"addtoken failed")
+	}
+	return err
+}