-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
sshkey.go
86 lines (71 loc) · 1.69 KB
/
sshkey.go
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
package db
import (
"crypto/sha256"
"encoding/base64"
"golang.org/x/crypto/ssh"
"gorm.io/gorm"
"time"
)
type SSHKey struct {
ID uint `gorm:"primaryKey"`
Title string
Content string
SHA string
CreatedAt int64
LastUsedAt int64
UserID uint
User User `validate:"-" `
}
func (sshKey *SSHKey) BeforeCreate(*gorm.DB) error {
pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey.Content))
if err != nil {
return err
}
sha := sha256.Sum256(pubKey.Marshal())
sshKey.SHA = base64.StdEncoding.EncodeToString(sha[:])
return nil
}
func GetSSHKeysByUserID(userId uint) ([]*SSHKey, error) {
var sshKeys []*SSHKey
err := db.
Where("user_id = ?", userId).
Order("created_at asc").
Find(&sshKeys).Error
return sshKeys, err
}
func GetSSHKeyByID(sshKeyId uint) (*SSHKey, error) {
sshKey := new(SSHKey)
err := db.
Where("id = ?", sshKeyId).
First(&sshKey).Error
return sshKey, err
}
func SSHKeyDoesExists(sshKeyContent string) (*SSHKey, error) {
sshKey := new(SSHKey)
err := db.
Where("content like ?", sshKeyContent+"%").
First(&sshKey).Error
return sshKey, err
}
func (sshKey *SSHKey) Create() error {
return db.Create(&sshKey).Error
}
func (sshKey *SSHKey) Delete() error {
return db.Delete(&sshKey).Error
}
func SSHKeyLastUsedNow(sshKeyContent string) error {
return db.Model(&SSHKey{}).
Where("content = ?", sshKeyContent).
Update("last_used_at", time.Now().Unix()).Error
}
// -- DTO -- //
type SSHKeyDTO struct {
Title string `form:"title" validate:"required,max=50"`
Content string `form:"content" validate:"required"`
}
func (dto *SSHKeyDTO) ToSSHKey() *SSHKey {
return &SSHKey{
Title: dto.Title,
Content: dto.Content,
}
}