databag/net/server/internal/api_addAccount.go

92 lines
2.1 KiB
Go
Raw Normal View History

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-19 20:07:57 +00:00
ErrResponse(w, http.StatusUnauthorized, res)
2022-01-17 05:11:24 +00:00
return
}
2022-01-19 23:03:06 +00:00
username, password, ret := BasicCredentials(r);
if ret != nil {
ErrResponse(w, http.StatusUnauthorized, ret)
2022-01-17 05:11:24 +00:00
return
}
// generate account key
2022-01-19 23:03:06 +00:00
privateKey, publicKey, keyType, err := GenerateRsaKeyPair()
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
2022-01-17 05:11:24 +00:00
privatePem := ExportRsaPrivateKeyAsPemStr(privateKey)
publicPem, err := ExportRsaPublicKeyAsPemStr(publicKey)
if err != nil {
2022-01-19 20:07:57 +00:00
ErrResponse(w, http.StatusInternalServerError, err)
2022-01-17 05:11:24 +00:00
return
}
// compute key fingerprint
msg := []byte(publicPem)
hash := sha256.Sum256(msg)
fingerprint := hex.EncodeToString(hash[:])
2022-01-17 05:11:24 +00:00
// create new account
account := store.Account{
Username: username,
Password: password,
Guid: fingerprint,
}
detail := store.AccountDetail{
PublicKey: publicPem,
PrivateKey: privatePem,
2022-01-19 23:03:06 +00:00
KeyType: keyType,
}
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(&detail).Error; res != nil {
return res;
}
account.AccountDetailID = detail.ID
2022-01-18 05:48:42 +00:00
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 {
2022-01-19 20:07:57 +00:00
ErrResponse(w, http.StatusInternalServerError, err)
2022-01-17 05:11:24 +00:00
return
}
// create response
profile := Profile{
Guid: account.Guid,
Handle: account.Username,
Name: detail.Name,
Description: detail.Description,
Location: detail.Location,
Image: detail.Image,
2022-01-17 05:11:24 +00:00
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)
}