From 40ac601c2d9a3e54eaf2511ed54804754f23494a Mon Sep 17 00:00:00 2001 From: Lukas Bachschwell Date: Thu, 15 Nov 2018 19:23:53 +0100 Subject: [PATCH] Delete and Create User working --- controllers/auth.go | 19 +++----- controllers/baseAPI.go | 20 ++++---- controllers/companyUser.go | 98 +++++++++++++++++++++++++++++--------- models/userCompanyMap.go | 9 ++++ 4 files changed, 102 insertions(+), 44 deletions(-) diff --git a/controllers/auth.go b/controllers/auth.go index 6536e66..0721079 100644 --- a/controllers/auth.go +++ b/controllers/auth.go @@ -109,18 +109,13 @@ func (c *AuthController) Login() { } tokenString := "" - if email == "admin@admin.at" && password == "my password" { - // The jwtClaims are our trusted clientside session - tokenString = tokenTools.CreateToken(jwt.MapClaims{ - "email": email, - "companyName": companyName, - "companyUserID": companyUserID, - "exp": time.Now().Unix() + 3600, - }) - } else { - c.ServeJSONError("Invalid user/password") - return - } + // The jwtClaims are our trusted clientside session + tokenString = tokenTools.CreateToken(jwt.MapClaims{ + "email": email, + "companyName": companyName, + "companyUserID": companyUserID, + "exp": time.Now().Unix() + 3600, + }) json := AuthResponse{200, tokenString, *companyUser} c.Data["json"] = &json diff --git a/controllers/baseAPI.go b/controllers/baseAPI.go index 5d49b28..a2740c5 100644 --- a/controllers/baseAPI.go +++ b/controllers/baseAPI.go @@ -47,15 +47,10 @@ func (c *BaseAPIController) Prepare() { jwtSession.Email = token["email"].(string) jwtSession.CompanyName = token["companyName"].(string) - jwtSession.CompanyUserID = token["companyUserID"].(int) - jwtSession.Exp = token["exp"].(time.Time) - - companyUser, err := models.GetCompanyUserById(o, int(jwtSession.CompanyUserID)) - if err != nil { - c.ServeJSONError("Error retrieving Company User") - return - } - currentUser = companyUser + 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) @@ -64,4 +59,11 @@ func (c *BaseAPIController) Prepare() { c.ServeJSONError("internal") return } + + companyUser, err := models.GetCompanyUserById(o, jwtSession.CompanyUserID) + if err != nil { + c.ServeJSONError("Error retrieving Company User") + return + } + currentUser = companyUser } diff --git a/controllers/companyUser.go b/controllers/companyUser.go index 2f90a29..5b93b8f 100644 --- a/controllers/companyUser.go +++ b/controllers/companyUser.go @@ -3,9 +3,11 @@ package controllers import ( "encoding/json" "errors" + "fmt" "multitenantStack/constants" "multitenantStack/models" "multitenantStack/services/companydb" + tokenTools "multitenantStack/services/tokenTools" "strconv" "strings" @@ -28,24 +30,67 @@ func (c *CompanyUserController) URLMapping() { // 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" // @Success 201 {int} models.CompanyUser // @Failure 403 body is empty // @router / [post] func (c *CompanyUserController) Post() { - var v models.CompanyUser - if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil { - if _, err := models.AddCompanyUser(o, &v); err == nil { - c.Ctx.Output.SetStatus(201) - c.Data["json"] = v - } else { - c.Data["json"] = err.Error() - } - } else { - c.Data["json"] = err.Error() + email := c.GetString("email") + password := c.GetString("password") + name := c.GetString("name") + + if email == "" || password == "" || name == "" { + c.ServeJSONError("Email/Password/Name missing") + return + } + + 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 ... @@ -165,7 +210,7 @@ func (c *CompanyUserController) Delete() { idStr := c.Ctx.Input.Param(":id") 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.ServeJSON() } @@ -175,26 +220,33 @@ func (c *CompanyUserController) Delete() { c.ServeJSON() } - if err := models.DeleteCompanyUser(o, id); err == nil { - c.Data["json"] = "OK" - } else { - c.Data["json"] = err.Error() + uExists, err := models.GetCompanyUserById(o, id) + if uExists == nil { + c.ServeJSONError("Error: User does not exist!") + 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 { c.ServeJSONError("Error deleting Company User") return } - systemDB := companydb.GetSystemDatabase() - systemO, err := orm.NewOrmWithDB("postgres", "default", systemDB) + fmt.Println(userCompanyMapping) + err = models.DeleteUserCompanyMap(systemO, userCompanyMapping.ID) if err != nil { c.ServeJSONError("Error deleting User Company Relation") return + } else { + c.ServeJSONSuccess("Successfully deleted!") } - - c.ServeJSON() } diff --git a/models/userCompanyMap.go b/models/userCompanyMap.go index e762991..075f283 100644 --- a/models/userCompanyMap.go +++ b/models/userCompanyMap.go @@ -54,6 +54,15 @@ func GetUserCompanyMapByEmail(o orm.Ormer, email string) (v *UserCompanyMap, 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 // no records exist func GetAllUserCompanyMap(o orm.Ormer, query map[string]string, fields []string, sortby []string, order []string,