summaryrefslogtreecommitdiffstats
path: root/models/migrations/v71.go
blob: c725908bd579eee99b1c05007b436f541968c342 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2018 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package migrations

import (
	"crypto/sha256"
	"fmt"

	"github.com/go-xorm/xorm"
	"golang.org/x/crypto/pbkdf2"

	"code.gitea.io/gitea/modules/generate"
	"code.gitea.io/gitea/modules/util"
)

func addScratchHash(x *xorm.Engine) error {
	// TwoFactor see models/twofactor.go
	type TwoFactor struct {
		ID               int64 `xorm:"pk autoincr"`
		UID              int64 `xorm:"UNIQUE"`
		Secret           string
		ScratchToken     string
		ScratchSalt      string
		ScratchHash      string
		LastUsedPasscode string         `xorm:"VARCHAR(10)"`
		CreatedUnix      util.TimeStamp `xorm:"INDEX created"`
		UpdatedUnix      util.TimeStamp `xorm:"INDEX updated"`
	}

	if err := x.Sync2(new(TwoFactor)); err != nil {
		return fmt.Errorf("Sync2: %v", err)
	}

	sess := x.NewSession()
	defer sess.Close()

	if err := sess.Begin(); err != nil {
		return err
	}

	// transform all tokens to hashes
	const batchSize = 100
	for start := 0; ; start += batchSize {
		tfas := make([]*TwoFactor, 0, batchSize)
		if err := x.Limit(batchSize, start).Find(&tfas); err != nil {
			return err
		}
		if len(tfas) == 0 {
			break
		}

		for _, tfa := range tfas {
			// generate salt
			salt, err := generate.GetRandomString(10)
			if err != nil {
				return err
			}
			tfa.ScratchSalt = salt
			tfa.ScratchHash = hashToken(tfa.ScratchToken, salt)

			if _, err := sess.ID(tfa.ID).Cols("scratch_salt, scratch_hash").Update(tfa); err != nil {
				return fmt.Errorf("couldn't add in scratch_hash and scratch_salt: %v", err)
			}

		}
	}

	// Commit and begin new transaction for dropping columns
	if err := sess.Commit(); err != nil {
		return err
	}
	if err := sess.Begin(); err != nil {
		return err
	}

	if err := dropTableColumns(sess, "two_factor", "scratch_token"); err != nil {
		return err
	}
	return sess.Commit()

}

func hashToken(token, salt string) string {
	tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New)
	return fmt.Sprintf("%x", tempHash)
}