mirror of
https://github.com/thomiceli/opengist.git
synced 2025-06-13 13:57:13 +02:00
Refactor server code (#407)
This commit is contained in:
71
internal/web/handlers/settings/sshkey.go
Normal file
71
internal/web/handlers/settings/sshkey.go
Normal file
@ -0,0 +1,71 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"github.com/thomiceli/opengist/internal/db"
|
||||
"github.com/thomiceli/opengist/internal/i18n"
|
||||
"github.com/thomiceli/opengist/internal/validator"
|
||||
"github.com/thomiceli/opengist/internal/web/context"
|
||||
"golang.org/x/crypto/ssh"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func SshKeysProcess(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
|
||||
dto := new(db.SSHKeyDTO)
|
||||
if err := ctx.Bind(dto); err != nil {
|
||||
return ctx.ErrorRes(400, ctx.Tr("error.cannot-bind-data"), err)
|
||||
}
|
||||
|
||||
if err := ctx.Validate(dto); err != nil {
|
||||
ctx.AddFlash(validator.ValidationMessages(&err, ctx.GetData("locale").(*i18n.Locale)), "error")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
key := dto.ToSSHKey()
|
||||
|
||||
key.UserID = user.ID
|
||||
|
||||
pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key.Content))
|
||||
if err != nil {
|
||||
ctx.AddFlash(ctx.Tr("flash.user.invalid-ssh-key"), "error")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
key.Content = strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pubKey)))
|
||||
|
||||
if exists, err := db.SSHKeyDoesExists(key.Content); exists {
|
||||
if err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot check if SSH key exists", err)
|
||||
}
|
||||
ctx.AddFlash(ctx.Tr("settings.ssh-key-exists"), "error")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
if err := key.Create(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot add SSH key", err)
|
||||
}
|
||||
|
||||
ctx.AddFlash(ctx.Tr("flash.user.ssh-key-added"), "success")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
func SshKeysDelete(ctx *context.Context) error {
|
||||
user := ctx.User
|
||||
keyId, err := strconv.Atoi(ctx.Param("id"))
|
||||
if err != nil {
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
key, err := db.GetSSHKeyByID(uint(keyId))
|
||||
|
||||
if err != nil || key.UserID != user.ID {
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
||||
|
||||
if err := key.Delete(); err != nil {
|
||||
return ctx.ErrorRes(500, "Cannot delete SSH key", err)
|
||||
}
|
||||
|
||||
ctx.AddFlash(ctx.Tr("flash.user.ssh-key-deleted"), "success")
|
||||
return ctx.RedirectTo("/settings")
|
||||
}
|
Reference in New Issue
Block a user