databag/net/server/internal/api_addAccountApp.go

82 lines
2.0 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"
"github.com/theckman/go-securerandom"
"gorm.io/gorm"
"net/http"
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")
// parse requested notifications
var notifications []Notification
if err := ParseRequest(r, w, &notifications); err != nil {
2022-11-15 17:10:01 +00:00
ErrMsg(err);
2022-07-22 19:28:14 +00:00
}
// 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
2022-11-15 17:10:01 +00:00
session.PushEnabled = true
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 {
pushEvent := &store.PushEvent{}
pushEvent.SessionID = session.ID
pushEvent.Event = notification.Event
pushEvent.MessageTitle = notification.MessageTitle
pushEvent.MessageBody = notification.MessageBody
if res := tx.Save(pushEvent).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
}