aboutsummaryrefslogtreecommitdiff
path: root/models/publickey.go
blob: bc9fbb33bd52972d30b7e20fc84287089e58c700 (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
package models

import (
	"fmt"
	"os"
	"path/filepath"
	"time"
)

var (
	publicKeyRootPath string
	tmplPublicKey     = "### autogenerated by gitgos, DO NOT EDIT\n" +
		"command=\"gitosis-serve %s\",no-port-forwarding," +
		"no-X11-forwarding,no-agent-forwarding,no-pty %s"
)

type PublicKey struct {
	Id      int64
	OwnerId int64     `xorm:"index"`
	Name    string    `xorm:"unique not null"`
	Content string    `xorm:"text not null"`
	Created time.Time `xorm:"created"`
	Updated time.Time `xorm:"updated"`
}

func GenAuthorizedKey(user, key string) string {
	return fmt.Sprintf(tmplPublicKey, user, key)
}

func AddPublicKey(key *PublicKey, user string) error {
	_, err := orm.Insert(key)
	if err != nil {
		return err
	}

	err = SaveAuthorizedKeyFile(user, key.Content)
	if err != nil {
		_, err2 := orm.Delete(key)
		if err2 != nil {
			// TODO: logo the error
		}
		return err
	}

	return nil
}

func SaveAuthorizedKeyFile(user, key string) error {
	f, err := os.Create(filepath.Join(publicKeyRootPath, user+".pub"))
	if err != nil {
		return err
	}
	_, err = f.WriteString(GenAuthorizedKey(user, key))
	return err
}