2022-01-18 06:56:00 +00:00
|
|
|
package databag
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"encoding/hex"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"databag/internal/store"
|
|
|
|
"github.com/theckman/go-securerandom"
|
|
|
|
)
|
|
|
|
|
|
|
|
func SetAccountApp(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
|
|
|
token, res := BearerAccountToken(r);
|
2022-03-08 18:18:31 +00:00
|
|
|
if res != nil || token.TokenType != APP_ACCOUNTATTACH {
|
|
|
|
ErrResponse(w, http.StatusUnauthorized, res)
|
2022-01-18 06:56:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// parse app data
|
|
|
|
var appData AppData
|
2022-03-08 18:18:31 +00:00
|
|
|
if res = ParseRequest(r, w, &appData); res != nil {
|
|
|
|
ErrResponse(w, http.StatusBadRequest, res)
|
2022-01-18 06:56:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// gernate app token
|
2022-01-22 19:40:20 +00:00
|
|
|
data, err := securerandom.Bytes(APP_TOKENSIZE)
|
2022-01-18 06:56:00 +00:00
|
|
|
if err != nil {
|
2022-03-08 18:18:31 +00:00
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
2022-01-18 06:56:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
access := hex.EncodeToString(data)
|
|
|
|
|
|
|
|
// create app entry
|
|
|
|
app := store.App {
|
2022-01-22 18:16:33 +00:00
|
|
|
AccountID: token.Account.Guid,
|
2022-01-18 06:56:00 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
if res := store.DB.Delete(token).Error; res != nil {
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
return nil;
|
|
|
|
});
|
|
|
|
if err != nil {
|
2022-03-08 18:18:31 +00:00
|
|
|
ErrResponse(w, http.StatusInternalServerError, err)
|
2022-01-18 06:56:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
WriteResponse(w, access)
|
|
|
|
}
|