databag/net/server/internal/api_addAccountApp.go

89 lines
2.2 KiB
Go
Raw Normal View History

2022-01-18 05:48:42 +00:00
package databag
import (
2022-07-22 19:28:14 +00:00
"databag/internal/store"
"encoding/hex"
"encoding/json"
2022-07-22 19:28:14 +00:00
"github.com/theckman/go-securerandom"
"gorm.io/gorm"
"net/http"
"errors"
2022-01-18 05:48:42 +00:00
)
2022-07-25 04:43:58 +00:00
//AddAccountApp with access token, attach an app to an account generating agent token
2022-01-18 05:48:42 +00:00
func AddAccountApp(w http.ResponseWriter, r *http.Request) {
2022-07-22 19:28:14 +00:00
account, res := AccountLogin(r)
if res != nil {
ErrResponse(w, http.StatusUnauthorized, res)
return
}
// parse authentication token
appName := r.FormValue("appName")
appVersion := r.FormValue("appVersion")
platform := r.FormValue("platform")
deviceToken := r.FormValue("deviceToken")
var notifications []string
if r.FormValue("notifications") != "" {
if err := json.Unmarshal([]byte(r.FormValue("notifications")), &notifications); err != nil {
ErrResponse(w, http.StatusBadRequest, errors.New("invalid notification types"));
return;
}
}
2022-07-22 19:28:14 +00:00
// parse app data
var appData AppData
if err := ParseRequest(r, w, &appData); err != nil {
ErrResponse(w, http.StatusBadRequest, err)
return
}
// gernate app token
data, err := securerandom.Bytes(APPTokenSize)
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
access := hex.EncodeToString(data)
login := LoginAccess{
GUID: account.GUID,
AppToken: account.GUID + "." + access,
2022-11-09 22:38:45 +00:00
PushSupported: getBoolConfigValue(CNFPushSupported, true),
2022-07-22 19:28:14 +00:00
}
// save app and delete token
err = store.DB.Transaction(func(tx *gorm.DB) error {
// create session
session := &store.Session{}
session.AccountID = account.GUID
session.Token = access
session.AppName = appName
session.AppVersion = appVersion
session.Platform = platform
session.PushToken = deviceToken
if res := tx.Save(session).Error; res != nil {
2022-07-22 19:28:14 +00:00
return res
}
login.Created = session.Created
for _, notification := range notifications {
eventType := &store.EventType{}
eventType.SessionID = session.ID
eventType.Name = notification
if res := tx.Save(eventType).Error; res != nil {
return res
}
}
2022-07-22 19:28:14 +00:00
return nil
})
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
WriteResponse(w, login)
2022-01-18 05:48:42 +00:00
}