summary refs log tree commit diff stats
path: root/account/addtoken.go
blob: 1c36ad8f1bd8a6f0c4493a0f463766a3dab99ba4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package account

import (
	"log"
	"time"

	"tildegit.org/andinus/perseus/password"
	"tildegit.org/andinus/perseus/storage"
)

// addToken will generate a random token, add it to database and
// return the token.
func (u *User) addToken(db *storage.DB) error {
	u.Token = password.RandStr(64)

	// Set user id from username.
	err := u.GetID(db)
	if err != nil {
		log.Printf("account/addtoken.go: %s\n",
			"failed to get id from username")
		return err
	}

	// Acquire write lock on the database.
	db.Mu.Lock()
	defer db.Mu.Unlock()

	// Start the transaction
	tx, err := db.Conn.Begin()
	defer tx.Rollback()
	if err != nil {
		log.Printf("account/addtoken.go: %s\n",
			"failed to begin transaction")
		return err
	}

	stmt, err := db.Conn.Prepare(`
INSERT INTO access(id, token, genTime) values(?, ?, ?)`)
	if err != nil {
		log.Printf("account/addtoken.go: %s\n",
			"failed to prepare statement")
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(u.ID, u.Token, time.Now().UTC())
	if err != nil {
		log.Printf("account/addtoken.go: %s\n",
			"failed to execute statement")
		return err
	}

	tx.Commit()
	return err

}