moltzaum commented on a change in pull request #2834: TO Golang: Rewrite /api/*/users endpoints URL: https://github.com/apache/trafficcontrol/pull/2834#discussion_r220034093
########## File path: traffic_ops/traffic_ops_golang/user/user.go ########## @@ -0,0 +1,445 @@ +package user + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import ( + "database/sql" + "errors" + "fmt" + "net/http" + "strconv" + + "github.com/apache/trafficcontrol/lib/go-tc" + "github.com/apache/trafficcontrol/lib/go-tc/tovalidate" + "github.com/apache/trafficcontrol/lib/go-util" + "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api" + "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/auth" + "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/dbhelpers" + "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant" + + "github.com/go-ozzo/ozzo-validation" + "github.com/go-ozzo/ozzo-validation/is" +) + +type TOUser struct { + ReqInfo *api.APIInfo `json:"-"` + tc.User +} + +func GetTypeSingleton() api.CRUDFactory { + return func(reqInfo *api.APIInfo) api.CRUDer { + toReturn := TOUser{reqInfo, tc.User{}} + return &toReturn + } +} + +func (user TOUser) GetKeyFieldsInfo() []api.KeyFieldInfo { + return []api.KeyFieldInfo{{Field: "id", Func: api.GetIntKey}} +} + +func (user TOUser) GetKeys() (map[string]interface{}, bool) { + if user.ID == nil { + return map[string]interface{}{"id": 0}, false + } + return map[string]interface{}{"id": *user.ID}, true +} + +func (user TOUser) GetAuditName() string { + if user.Username != nil { + return *user.Username + } + if user.ID != nil { + return strconv.Itoa(*user.ID) + } + return "unknown" +} + +func (user TOUser) GetType() string { + return "user" +} + +func (user *TOUser) SetKeys(keys map[string]interface{}) { + i, _ := keys["id"].(int) // non-panicking type assertion + user.ID = &i +} + +func (v *TOUser) APIInfo() *api.APIInfo { + return v.ReqInfo +} + +func (user *TOUser) SetLastUpdated(t tc.TimeNoMod) { + user.LastUpdated = &t +} + +func (user *TOUser) NewReadObj() interface{} { + return &tc.User{} +} + +func (user *TOUser) ParamColumns() map[string]dbhelpers.WhereColumnInfo { + return map[string]dbhelpers.WhereColumnInfo{ + "id": dbhelpers.WhereColumnInfo{"u.id", api.IsInt}, + "tenant": dbhelpers.WhereColumnInfo{"t.name", nil}, + "username": dbhelpers.WhereColumnInfo{"username", nil}, + } +} + +func (user *TOUser) Validate() error { + + validateErrs := validation.Errors{ + "email": validation.Validate(user.Email, validation.Required, is.Email), + "fullName": validation.Validate(user.FullName, validation.Required), + "role": validation.Validate(user.Role, validation.Required), + "username": validation.Validate(user.Username, validation.Required), + "tenantID": validation.Validate(user.TenantID, validation.Required), + } + + // Passwords are not required for update + if user.LocalPassword != nil && user.ConfirmLocalPassword != nil { + + if *user.LocalPassword != *user.ConfirmLocalPassword { + return errors.New("Passwords should match.") + } + + _, err := auth.IsGoodLoginPair(*user.LocalPassword, *user.Username) + if err != nil { + return err + } + } + + return util.JoinErrs(tovalidate.ToErrors(validateErrs)) +} + +func (user *TOUser) postValidate() error { + validateErrs := validation.Errors{ + "localPasswd": validation.Validate(user.LocalPassword, validation.Required), + "confirmLocalPasswd": validation.Validate(user.ConfirmLocalPassword, validation.Required), + } + return util.JoinErrs(tovalidate.ToErrors(validateErrs)) +} + +// Note: Not using GenericCreate because Scan also needs to scan tenant and rolename +func (user *TOUser) Create() (error, error, int) { + + // PUT and POST validation differs slightly + err := user.postValidate() + if err != nil { + return err, nil, http.StatusBadRequest + } + + // Convert password to SCRYPT + *user.LocalPassword, err = auth.DerivePassword(*user.LocalPassword) + if err != nil { + return err, nil, http.StatusBadRequest + } + *user.ConfirmLocalPassword, err = auth.DerivePassword(*user.ConfirmLocalPassword) + if err != nil { + return err, nil, http.StatusBadRequest + } + + resultRows, err := user.ReqInfo.Tx.NamedQuery(user.InsertQuery(), user) + if err != nil { + return api.ParseDBError(err) + } + defer resultRows.Close() + + var id int + var lastUpdated tc.TimeNoMod + var tenant string + var rolename string + + rowsAffected := 0 + for resultRows.Next() { + rowsAffected++ + if err = resultRows.Scan(&id, &lastUpdated, &tenant, &rolename); err != nil { + return nil, fmt.Errorf("could not scan after insert: %s\n)", err), http.StatusInternalServerError + } + } + + if rowsAffected == 0 { + return nil, fmt.Errorf("no user was inserted, nothing was returned"), http.StatusInternalServerError + } else if rowsAffected > 1 { + return nil, fmt.Errorf("too many rows affected from user insert"), http.StatusInternalServerError + } + + user.ID = &id + user.LastUpdated = &lastUpdated + user.Tenant = &tenant + user.RoleName = &rolename + user.LocalPassword = nil + user.ConfirmLocalPassword = nil + + return nil, nil, http.StatusOK +} + +// returning true indicates the data related to the given tenantID should be visible +// this is just a linear search;`tenantIDs` is presumed to be unsorted +func checkTenancy(tenantID *int, tenantIDs []int) bool { + for _, id := range tenantIDs { + if id == *tenantID { + return true + } + } + return false +} + +// This is not using GenericRead because of this tenancy check. Maybe we can add tenancy functionality to the generic case? Review comment: You referenced the update handler. I believe that also applies to create and delete as well, but not read. Read won't tell you that you don't have access, but rather filters out what you don't have and only shows you what you do have. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
