2023-09-02 22:30:57 +00:00
|
|
|
package db
|
2023-03-14 15:22:52 +00:00
|
|
|
|
2023-04-17 12:25:39 +00:00
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"time"
|
|
|
|
)
|
2023-03-14 15:22:52 +00:00
|
|
|
|
|
|
|
type SSHKey struct {
|
2023-03-17 13:56:39 +00:00
|
|
|
ID uint `gorm:"primaryKey"`
|
|
|
|
Title string
|
|
|
|
Content string
|
2023-03-14 15:22:52 +00:00
|
|
|
SHA string
|
|
|
|
CreatedAt int64
|
|
|
|
LastUsedAt int64
|
|
|
|
UserID uint
|
|
|
|
User User `validate:"-" `
|
|
|
|
}
|
|
|
|
|
2023-04-17 12:25:39 +00:00
|
|
|
func (sshKey *SSHKey) BeforeCreate(tx *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
|
|
|
|
}
|
|
|
|
|
2023-03-14 15:22:52 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-05-01 00:55:34 +00:00
|
|
|
func SSHKeyDoesExists(sshKeyContent string) (*SSHKey, error) {
|
2023-03-14 15:22:52 +00:00
|
|
|
sshKey := new(SSHKey)
|
|
|
|
err := db.
|
|
|
|
Where("content like ?", sshKeyContent+"%").
|
|
|
|
First(&sshKey).Error
|
|
|
|
|
|
|
|
return sshKey, err
|
|
|
|
}
|
|
|
|
|
2023-03-17 13:56:39 +00:00
|
|
|
func (sshKey *SSHKey) Create() error {
|
2023-03-14 15:22:52 +00:00
|
|
|
return db.Create(&sshKey).Error
|
|
|
|
}
|
|
|
|
|
2023-03-17 13:56:39 +00:00
|
|
|
func (sshKey *SSHKey) Delete() error {
|
2023-03-14 15:22:52 +00:00
|
|
|
return db.Delete(&sshKey).Error
|
|
|
|
}
|
|
|
|
|
2023-05-01 00:55:34 +00:00
|
|
|
func SSHKeyLastUsedNow(sshKeyContent string) error {
|
2023-03-14 15:22:52 +00:00
|
|
|
return db.Model(&SSHKey{}).
|
2023-05-01 00:55:34 +00:00
|
|
|
Where("content = ?", sshKeyContent).
|
2023-03-14 15:22:52 +00:00
|
|
|
Update("last_used_at", time.Now().Unix()).Error
|
|
|
|
}
|
2023-03-17 13:56:39 +00:00
|
|
|
|
|
|
|
// -- 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,
|
|
|
|
}
|
|
|
|
}
|