databag/net/server/internal/api_addAccountApp.go

59 lines
1.2 KiB
Go
Raw Normal View History

2022-01-18 05:48:42 +00:00
package databag
import (
"net/http"
"encoding/hex"
2022-03-11 21:40:29 +00:00
"gorm.io/gorm"
2022-01-18 05:48:42 +00:00
"databag/internal/store"
"github.com/theckman/go-securerandom"
)
func AddAccountApp(w http.ResponseWriter, r *http.Request) {
2022-03-11 21:40:29 +00:00
account, res := AccountLogin(r)
if res != nil {
ErrResponse(w, http.StatusUnauthorized, res)
2022-01-18 05:48:42 +00:00
return
}
2022-03-11 21:40:29 +00:00
// parse app data
var appData AppData
if err := ParseRequest(r, w, &appData); err != nil {
ErrResponse(w, http.StatusBadRequest, err)
2022-01-18 05:48:42 +00:00
return
}
2022-03-11 21:40:29 +00:00
// gernate app token
data, err := securerandom.Bytes(APP_TOKENSIZE)
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
2022-03-08 18:18:31 +00:00
}
2022-03-11 21:40:29 +00:00
access := hex.EncodeToString(data)
// create app entry
app := store.App {
AccountID: account.Guid,
Name: appData.Name,
Description: appData.Description,
Image: appData.Image,
Url: appData.Url,
Token: access,
};
// save app and delete token
err = store.DB.Transaction(func(tx *gorm.DB) error {
if res := store.DB.Create(&app).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-18 05:48:42 +00:00
return
}
2022-03-11 21:40:29 +00:00
WriteResponse(w, account.Guid + "." + access)
2022-01-18 05:48:42 +00:00
}