Delete and Create User working

This commit is contained in:
Lukas Bachschwell 2018-11-15 19:23:53 +01:00
parent c19f60f565
commit 40ac601c2d
4 changed files with 102 additions and 44 deletions

View File

@ -109,18 +109,13 @@ func (c *AuthController) Login() {
} }
tokenString := "" tokenString := ""
if email == "admin@admin.at" && password == "my password" { // The jwtClaims are our trusted clientside session
// The jwtClaims are our trusted clientside session tokenString = tokenTools.CreateToken(jwt.MapClaims{
tokenString = tokenTools.CreateToken(jwt.MapClaims{ "email": email,
"email": email, "companyName": companyName,
"companyName": companyName, "companyUserID": companyUserID,
"companyUserID": companyUserID, "exp": time.Now().Unix() + 3600,
"exp": time.Now().Unix() + 3600, })
})
} else {
c.ServeJSONError("Invalid user/password")
return
}
json := AuthResponse{200, tokenString, *companyUser} json := AuthResponse{200, tokenString, *companyUser}
c.Data["json"] = &json c.Data["json"] = &json

View File

@ -47,15 +47,10 @@ func (c *BaseAPIController) Prepare() {
jwtSession.Email = token["email"].(string) jwtSession.Email = token["email"].(string)
jwtSession.CompanyName = token["companyName"].(string) jwtSession.CompanyName = token["companyName"].(string)
jwtSession.CompanyUserID = token["companyUserID"].(int) companyUserIDFloat := token["companyUserID"].(float64)
jwtSession.Exp = token["exp"].(time.Time) jwtSession.CompanyUserID = int(companyUserIDFloat)
ExpFloat := token["exp"].(float64)
companyUser, err := models.GetCompanyUserById(o, int(jwtSession.CompanyUserID)) jwtSession.Exp = time.Unix(int64(ExpFloat), 0)
if err != nil {
c.ServeJSONError("Error retrieving Company User")
return
}
currentUser = companyUser
companyDB = db companyDB = db
o, err = orm.NewOrmWithDB("postgres", "company", companyDB) o, err = orm.NewOrmWithDB("postgres", "company", companyDB)
@ -64,4 +59,11 @@ func (c *BaseAPIController) Prepare() {
c.ServeJSONError("internal") c.ServeJSONError("internal")
return return
} }
companyUser, err := models.GetCompanyUserById(o, jwtSession.CompanyUserID)
if err != nil {
c.ServeJSONError("Error retrieving Company User")
return
}
currentUser = companyUser
} }

View File

@ -3,9 +3,11 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"multitenantStack/constants" "multitenantStack/constants"
"multitenantStack/models" "multitenantStack/models"
"multitenantStack/services/companydb" "multitenantStack/services/companydb"
tokenTools "multitenantStack/services/tokenTools"
"strconv" "strconv"
"strings" "strings"
@ -28,24 +30,67 @@ func (c *CompanyUserController) URLMapping() {
// Post ... // Post ...
// @Title Post // @Title Post
// @Description create CompanyUser // @Description Create a new CompanyUser and his user company mapping
// @Param body body models.CompanyUser true "body for CompanyUser content" // @Param body body models.CompanyUser true "body for CompanyUser content"
// @Success 201 {int} models.CompanyUser // @Success 201 {int} models.CompanyUser
// @Failure 403 body is empty // @Failure 403 body is empty
// @router / [post] // @router / [post]
func (c *CompanyUserController) Post() { func (c *CompanyUserController) Post() {
var v models.CompanyUser email := c.GetString("email")
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil { password := c.GetString("password")
if _, err := models.AddCompanyUser(o, &v); err == nil { name := c.GetString("name")
c.Ctx.Output.SetStatus(201)
c.Data["json"] = v if email == "" || password == "" || name == "" {
} else { c.ServeJSONError("Email/Password/Name missing")
c.Data["json"] = err.Error() return
} }
} else {
c.Data["json"] = err.Error() systemdb := companydb.GetSystemDatabase()
if systemdb == nil {
c.ServeJSONError("Error retrieving User")
return
}
systemO, err := orm.NewOrmWithDB("postgres", "default", systemdb)
if err != nil {
c.ServeJSONError("Error retrieving User")
return
}
ucmExists, err := models.GetUserCompanyMapByEmail(systemO, email)
if ucmExists != nil {
fmt.Println(ucmExists)
c.ServeJSONError("Error: Email exists!")
return
}
var companyUser models.CompanyUser
companyUser.Name = name
companyUser.Profile = "{}"
companyUser.Role = constants.RoleAdmin
companyUserId, err := models.AddCompanyUser(o, &companyUser)
if err != nil {
c.ServeJSONErrorWithError("Error on saving company user", err)
return
}
var userCompanyMapping models.UserCompanyMap
newHash, _ := tokenTools.HashPassword(password)
userCompanyMapping.PasswordHash = newHash
userCompanyMapping.CompanyUserID = int16(companyUserId)
userCompanyMapping.Company = jwtSession.CompanyName
userCompanyMapping.Email = email
_, err = models.AddUserCompanyMap(systemO, &userCompanyMapping)
if err == nil {
c.ServeJSONSuccess("Success")
return
} else {
c.ServeJSONErrorWithError("Error on saving user", err)
return
} }
c.ServeJSON()
} }
// GetOne ... // GetOne ...
@ -165,7 +210,7 @@ func (c *CompanyUserController) Delete() {
idStr := c.Ctx.Input.Param(":id") idStr := c.Ctx.Input.Param(":id")
id, _ := strconv.Atoi(idStr) id, _ := strconv.Atoi(idStr)
if currentUser.Id != id { if currentUser.Role != constants.RoleAdmin && currentUser.Id != id {
c.ServeJSONError("You can not delete users other than yourself!") c.ServeJSONError("You can not delete users other than yourself!")
c.ServeJSON() c.ServeJSON()
} }
@ -175,26 +220,33 @@ func (c *CompanyUserController) Delete() {
c.ServeJSON() c.ServeJSON()
} }
if err := models.DeleteCompanyUser(o, id); err == nil { uExists, err := models.GetCompanyUserById(o, id)
c.Data["json"] = "OK" if uExists == nil {
} else { c.ServeJSONError("Error: User does not exist!")
c.Data["json"] = err.Error() return
} }
// After deleting the user here we need to delete the same User in the system DB err = models.DeleteCompanyUser(o, id)
if err != nil {
c.ServeJSONError("Failed to delete company User")
}
userCompanyMapping, err := models.GetUserCompanyMapByEmail(o, jwtSession.Email) systemDB := companydb.GetSystemDatabase()
systemO, err := orm.NewOrmWithDB("postgres", "default", systemDB)
// After deleting the user here we need to delete the same User in the system DB
userCompanyMapping, err := models.GetUserCompanyMapByCompanyAndCID(systemO, jwtSession.CompanyName, int16(id))
if err != nil { if err != nil {
c.ServeJSONError("Error deleting Company User") c.ServeJSONError("Error deleting Company User")
return return
} }
systemDB := companydb.GetSystemDatabase() fmt.Println(userCompanyMapping)
systemO, err := orm.NewOrmWithDB("postgres", "default", systemDB)
err = models.DeleteUserCompanyMap(systemO, userCompanyMapping.ID) err = models.DeleteUserCompanyMap(systemO, userCompanyMapping.ID)
if err != nil { if err != nil {
c.ServeJSONError("Error deleting User Company Relation") c.ServeJSONError("Error deleting User Company Relation")
return return
} else {
c.ServeJSONSuccess("Successfully deleted!")
} }
c.ServeJSON()
} }

View File

@ -54,6 +54,15 @@ func GetUserCompanyMapByEmail(o orm.Ormer, email string) (v *UserCompanyMap, err
return nil, err return nil, err
} }
// GetUserCompanyMapByEmail retrieves UserCompanyMap by email. Returns error if email doesn't exist
func GetUserCompanyMapByCompanyAndCID(o orm.Ormer, company string, companyUserID int16) (v *UserCompanyMap, err error) {
v = &UserCompanyMap{}
if o.QueryTable(v.TableName()).Filter("company", company).Filter("company_user_id", companyUserID).One(v); err == nil {
return v, nil
}
return nil, err
}
// GetAllUserCompanyMap retrieves all UserCompanyMap matches certain condition. Returns empty list if // GetAllUserCompanyMap retrieves all UserCompanyMap matches certain condition. Returns empty list if
// no records exist // no records exist
func GetAllUserCompanyMap(o orm.Ormer, query map[string]string, fields []string, sortby []string, order []string, func GetAllUserCompanyMap(o orm.Ormer, query map[string]string, fields []string, sortby []string, order []string,