multitenantStack/controllers/baseAPI.go

71 lines
1.6 KiB
Go
Raw Normal View History

2018-11-07 10:10:51 +00:00
package controllers
import (
"database/sql"
"fmt"
2018-11-15 17:10:24 +00:00
"multitenantStack/models"
companydb "multitenantStack/services/companydb"
2018-11-15 17:10:24 +00:00
"time"
"github.com/astaxie/beego/orm"
)
// BaseAPIController operations for APIs
2018-11-07 10:10:51 +00:00
type BaseAPIController struct {
BaseController
}
2018-11-16 19:01:49 +00:00
// SessionData holds all vars for a user from user company map
2018-11-15 17:10:24 +00:00
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
}
2018-11-15 17:10:24 +00:00
jwtSession.Email = token["email"].(string)
jwtSession.CompanyName = token["companyName"].(string)
2018-11-15 18:23:53 +00:00
companyUserIDFloat := token["companyUserID"].(float64)
jwtSession.CompanyUserID = int(companyUserIDFloat)
ExpFloat := token["exp"].(float64)
jwtSession.Exp = time.Unix(int64(ExpFloat), 0)
2018-11-15 17:10:24 +00:00
companyDB = db
o, err = orm.NewOrmWithDB("postgres", "company", companyDB)
if err != nil {
fmt.Println(err.Error())
c.ServeJSONError("internal")
return
}
2018-11-15 18:23:53 +00:00
companyUser, err := models.GetCompanyUserById(o, jwtSession.CompanyUserID)
if err != nil {
c.ServeJSONError("Error retrieving Company User")
return
}
currentUser = companyUser
2018-11-07 10:10:51 +00:00
}