multitenantStack/controllers/baseAPI.go

70 lines
1.5 KiB
Go

package controllers
import (
"database/sql"
"fmt"
"multitenantStack/models"
companydb "multitenantStack/services/companydb"
"time"
"github.com/astaxie/beego/orm"
)
// BaseAPIController operations for APIs
type BaseAPIController struct {
BaseController
}
type SessionData struct {
Email string
CompanyName string
CompanyUserID int
Exp time.Time
}
var jwtSession SessionData
var currentUser *models.CompanyUser
var companyDB *sql.DB
var o orm.Ormer
//var database sql.database
// Prepare parse all requests that come after this controller for valid auth
func (c *BaseAPIController) Prepare() {
tokenString := c.Ctx.Request.Header.Get("X-JWTtoken")
if tokenString == "" {
c.ServeJSONError("No Token provided")
return
}
token, db, err := companydb.GetDatabase(tokenString)
if err != nil {
c.ServeJSONError("Token invalid")
return
}
jwtSession.Email = token["email"].(string)
jwtSession.CompanyName = token["companyName"].(string)
companyUserIDFloat := token["companyUserID"].(float64)
jwtSession.CompanyUserID = int(companyUserIDFloat)
ExpFloat := token["exp"].(float64)
jwtSession.Exp = time.Unix(int64(ExpFloat), 0)
companyDB = db
o, err = orm.NewOrmWithDB("postgres", "company", companyDB)
if err != nil {
fmt.Println(err.Error())
c.ServeJSONError("internal")
return
}
companyUser, err := models.GetCompanyUserById(o, jwtSession.CompanyUserID)
if err != nil {
c.ServeJSONError("Error retrieving Company User")
return
}
currentUser = companyUser
}