databag/net/server/internal/setNodeClaim_endpoint.go

58 lines
1.5 KiB
Go
Raw Normal View History

2022-01-15 21:45:37 +00:00
package databag
import (
2022-01-16 07:25:43 +00:00
"errors"
2022-01-15 21:45:37 +00:00
"net/http"
"gorm.io/gorm"
"databag/internal/store"
"golang.org/x/crypto/bcrypt"
)
func SetNodeClaim(w http.ResponseWriter, r *http.Request) {
2022-01-16 07:25:43 +00:00
var config store.Config
err := store.DB.Where("config_id = ?", CONFIG_CONFIGURED).First(&config).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
w.WriteHeader(http.StatusInternalServerError)
return
}
if config.BoolValue {
2022-01-15 21:45:37 +00:00
w.WriteHeader(http.StatusUnauthorized)
return
}
username, password, ok := r.BasicAuth();
if !ok || username == "" || password == "" {
2022-01-16 07:25:43 +00:00
LogMsg("SetNodeClaim - invalid credenitals");
2022-01-15 21:45:37 +00:00
w.WriteHeader(http.StatusBadRequest)
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
2022-01-16 07:25:43 +00:00
LogMsg("SetNodeClaim - failed to hash password");
2022-01-15 21:45:37 +00:00
w.WriteHeader(http.StatusInternalServerError)
return
}
err = store.DB.Transaction(func(tx *gorm.DB) error {
if res := tx.Create(&store.Config{ConfigId: CONFIG_USERNAME, StrValue: username}).Error; res != nil {
return res
}
if res := tx.Create(&store.Config{ConfigId: CONFIG_PASSWORD, BinValue: hashedPassword}).Error; res != nil {
return res
}
if res := tx.Create(&store.Config{ConfigId: CONFIG_CONFIGURED, BoolValue: true}).Error; res != nil {
return res
}
return nil;
})
if(err != nil) {
2022-01-16 07:25:43 +00:00
LogMsg("SetNodeCalim - failed to store credentials");
2022-01-15 21:45:37 +00:00
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}