2022-01-17 05:11:24 +00:00
|
|
|
package databag
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/hex"
|
2022-01-18 05:48:42 +00:00
|
|
|
"gorm.io/gorm"
|
2022-01-17 05:11:24 +00:00
|
|
|
"databag/internal/store"
|
|
|
|
)
|
|
|
|
|
|
|
|
func AddAccount(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
2022-01-18 05:48:42 +00:00
|
|
|
token, res := BearerAccountToken(r);
|
|
|
|
if res != nil || token.TokenType != "create" {
|
2022-01-17 05:11:24 +00:00
|
|
|
LogMsg("authentication failed")
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-17 21:42:17 +00:00
|
|
|
username, password, err := BasicCredentials(r);
|
2022-01-17 05:11:24 +00:00
|
|
|
if err != nil {
|
|
|
|
LogMsg("invalid basic credentials")
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// generate account key
|
|
|
|
privateKey, publicKey := GenerateRsaKeyPair()
|
|
|
|
privatePem := ExportRsaPrivateKeyAsPemStr(privateKey)
|
|
|
|
publicPem, err := ExportRsaPublicKeyAsPemStr(publicKey)
|
|
|
|
if err != nil {
|
|
|
|
LogMsg("failed generate key")
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// compute key fingerprint
|
|
|
|
msg := []byte(publicPem)
|
|
|
|
hash := sha256.New()
|
|
|
|
if _, err = hash.Write(msg); err != nil {
|
|
|
|
LogMsg("failed to fingerprint key")
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fingerprint := hex.EncodeToString(hash.Sum(nil))
|
|
|
|
|
|
|
|
// create new account
|
|
|
|
account := store.Account{
|
|
|
|
PublicKey: publicPem,
|
|
|
|
PrivateKey: privatePem,
|
|
|
|
KeyType: "RSA4096",
|
|
|
|
Username: username,
|
|
|
|
Password: password,
|
|
|
|
Guid: fingerprint,
|
|
|
|
};
|
2022-01-18 05:48:42 +00:00
|
|
|
|
|
|
|
// save account and delete token
|
|
|
|
err = store.DB.Transaction(func(tx *gorm.DB) error {
|
|
|
|
if res := store.DB.Create(&account).Error; res != nil {
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
if res := store.DB.Delete(token).Error; res != nil {
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
return nil;
|
|
|
|
});
|
|
|
|
if err != nil {
|
|
|
|
LogMsg("failed to create account");
|
2022-01-17 05:11:24 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// create response
|
|
|
|
profile := Profile{
|
|
|
|
Guid: account.Guid,
|
|
|
|
Handle: account.Username,
|
|
|
|
Name: account.Name,
|
|
|
|
Description: account.Description,
|
|
|
|
Location: account.Location,
|
|
|
|
Image: account.Image,
|
|
|
|
Revision: account.ProfileRevision,
|
2022-01-17 05:55:25 +00:00
|
|
|
Version: APP_VERSION,
|
2022-01-17 05:11:24 +00:00
|
|
|
Node: "https://" + getStrConfigValue(CONFIG_DOMAIN, ""),
|
|
|
|
}
|
|
|
|
|
|
|
|
// send response
|
|
|
|
WriteResponse(w, profile)
|
|
|
|
}
|
|
|
|
|
|
|
|
|