From b21d60194efdbd19db6ecb63eceba16db496da78 Mon Sep 17 00:00:00 2001 From: Albin Antony Date: Wed, 11 Oct 2023 17:27:38 +0530 Subject: [PATCH] Add #204 Align onboard APIs --- src/common/utils.go | 22 ++++++ src/handlerv2/getorganizationbyid_handler.go | 32 +++++++- src/handlerv2/gettoken_handler.go | 13 +++- src/handlerv2/loginadminuser_handler.go | 29 ++++--- src/handlerv2/loginuser_handler.go | 45 ++++++++--- src/handlerv2/updateorganization_handler.go | 15 ++-- .../updateorganizationcoverimage_handler.go | 19 +++-- .../updateorganizationlogoimage_handler.go | 20 +++-- src/handlerv2/validatephonenumber_handler.go | 10 +-- src/handlerv2/validateuseremail_handler.go | 6 +- src/handlerv2/verifyotp_handler.go | 9 +-- src/handlerv2/verifyphonenumber_handler.go | 22 +++--- src/httppathsv2/routes.go | 2 +- src/otp/otps.go | 19 +++++ src/user/users.go | 76 +++++++++++++------ 15 files changed, 242 insertions(+), 97 deletions(-) diff --git a/src/common/utils.go b/src/common/utils.go index 515e715..2040044 100644 --- a/src/common/utils.go +++ b/src/common/utils.go @@ -39,6 +39,11 @@ type status struct { Message string } +type statusv2 struct { + ErrorCode int `json:"errorCode"` + ErrorDescription string `json:"errorDescription"` +} + // OrgRole Organization role definition type OrgRole struct { ID int @@ -133,6 +138,23 @@ func HandleError(w http.ResponseWriter, code int, message string, err error) { w.Write(response) } +func HandleErrorV2(w http.ResponseWriter, code int, message string, err error) { + s := statusv2{ + ErrorCode: code, + ErrorDescription: message, + } + response, _ := json.Marshal(s) + + pc, fn, line, _ := runtime.Caller(1) + + log.Printf("%v with err:%v in %s[%s:%d]", message, err, + filepath.Base(runtime.FuncForPC(pc).Name()), filepath.Base(fn), line) + + w.WriteHeader(code) + w.Header().Set("Content-Type", "application/json") + w.Write(response) +} + // GetRandomString Generate a random alpha numeric string of requested length func GetRandomString(length int) string { rand.Seed(time.Now().UnixNano()) diff --git a/src/handlerv2/getorganizationbyid_handler.go b/src/handlerv2/getorganizationbyid_handler.go index bf5641f..b0fd0ef 100644 --- a/src/handlerv2/getorganizationbyid_handler.go +++ b/src/handlerv2/getorganizationbyid_handler.go @@ -8,20 +8,46 @@ import ( "github.com/bb-consent/api/src/common" "github.com/bb-consent/api/src/config" "github.com/bb-consent/api/src/org" + "go.mongodb.org/mongo-driver/bson/primitive" ) +type organizationResp struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` + Name string `json:"name"` + Location string `json:"location"` + PolicyURL string `json:"policyUrl"` + CoverImageID string `json:"coverImageId"` + CoverImageURL string `json:"coverImageUrl"` + LogoImageID string `json:"logoImageId"` + LogoImageURL string `json:"logoImageUrl"` +} + +type getOrgResp struct { + Organization organizationResp `json:"organization"` +} + // GetOrganizationByID Gets a single organization by given id func GetOrganizationByID(w http.ResponseWriter, r *http.Request) { organizationID := r.Header.Get(config.OrganizationId) o, err := org.Get(organizationID) - if err != nil { m := fmt.Sprintf("Failed to get organization by ID :%v", organizationID) - common.HandleError(w, http.StatusNotFound, m, err) + common.HandleErrorV2(w, http.StatusNotFound, m, err) return } + oResp := organizationResp{ + ID: o.ID, + Name: o.Name, + Location: o.Location, + PolicyURL: o.PolicyURL, + CoverImageID: o.CoverImageID, + CoverImageURL: o.CoverImageURL, + LogoImageID: o.LogoImageID, + LogoImageURL: o.LogoImageURL, + } + w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) - response, _ := json.Marshal(organization{o}) + response, _ := json.Marshal(getOrgResp{oResp}) w.Write(response) } diff --git a/src/handlerv2/gettoken_handler.go b/src/handlerv2/gettoken_handler.go index 861700b..8fc5801 100644 --- a/src/handlerv2/gettoken_handler.go +++ b/src/handlerv2/gettoken_handler.go @@ -14,8 +14,8 @@ import ( ) type tokenReq struct { - RefreshToken string `valid:"required"` - ClientID string `valid:"required"` + RefreshToken string `valid:"required" json:"refreshToken"` + ClientID string `valid:"required" json:"clientId"` } // GetToken return access token when refresh token is given @@ -67,7 +67,14 @@ func GetToken(w http.ResponseWriter, r *http.Request) { var tok iamToken json.Unmarshal(body, &tok) - response, _ := json.Marshal(tok) + tResp := tokenResp{ + AccessToken: tok.AccessToken, + ExpiresIn: tok.ExpiresIn, + RefreshExpiresIn: tok.RefreshExpiresIn, + RefreshToken: tok.RefreshToken, + TokenType: tok.TokenType, + } + response, _ := json.Marshal(tResp) w.WriteHeader(resp.StatusCode) w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) w.Write(response) diff --git a/src/handlerv2/loginadminuser_handler.go b/src/handlerv2/loginadminuser_handler.go index c602cc4..21bece0 100644 --- a/src/handlerv2/loginadminuser_handler.go +++ b/src/handlerv2/loginadminuser_handler.go @@ -16,13 +16,16 @@ import ( ) type loginReq struct { - Username string `valid:"required,email"` - Password string `valid:"required"` + Username string `json:"username" valid:"required,email"` + Password string `json:"password" valid:"required"` } type loginResp struct { - User user.User - Token iamToken + AccessToken string `json:"accessToken"` + ExpiresIn int `json:"expiresIn"` + RefreshExpiresIn int `json:"refreshExpiresIn"` + RefreshToken string `json:"refreshToken"` + TokenType string `json:"tokenType"` } // LoginAdminUser Implements the admin users login @@ -39,7 +42,7 @@ func LoginAdminUser(w http.ResponseWriter, r *http.Request) { if !valid { log.Printf("Invalid request params for authentication") - common.HandleError(w, http.StatusBadRequest, err.Error(), err) + common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) return } @@ -53,33 +56,39 @@ func LoginAdminUser(w http.ResponseWriter, r *http.Request) { return } m := fmt.Sprintf("Failed to get token for user:%v", lReq.Username) - common.HandleError(w, status, m, err) + common.HandleErrorV2(w, status, m, err) return } accessToken, err := token.ParseToken(t.AccessToken) if err != nil { m := fmt.Sprintf("Failed to parse token for user:%v", lReq.Username) - common.HandleError(w, status, m, err) + common.HandleErrorV2(w, status, m, err) return } u, err := user.GetByIamID(accessToken.IamID) if err != nil { m := fmt.Sprintf("User: %v does not exist", lReq.Username) - common.HandleError(w, http.StatusUnauthorized, m, err) + common.HandleErrorV2(w, http.StatusUnauthorized, m, err) return } if len(u.Roles) == 0 { //Normal user can not login with this API. m := fmt.Sprintf("Non Admin User: %v tried admin login", lReq.Username) - common.HandleError(w, http.StatusForbidden, m, err) + common.HandleErrorV2(w, http.StatusForbidden, m, err) return } actionLog := fmt.Sprintf("%v logged in", u.Email) actionlog.LogOrgSecurityCalls(u.ID.Hex(), u.Email, u.Roles[0].OrgID, actionLog) - lResp := loginResp{u, t} + lResp := loginResp{ + AccessToken: t.AccessToken, + ExpiresIn: t.ExpiresIn, + RefreshExpiresIn: t.RefreshExpiresIn, + RefreshToken: t.RefreshToken, + TokenType: t.TokenType, + } resp, _ := json.Marshal(lResp) w.WriteHeader(http.StatusOK) w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) diff --git a/src/handlerv2/loginuser_handler.go b/src/handlerv2/loginuser_handler.go index 448f98d..81f7372 100644 --- a/src/handlerv2/loginuser_handler.go +++ b/src/handlerv2/loginuser_handler.go @@ -10,9 +10,23 @@ import ( "github.com/asaskevich/govalidator" "github.com/bb-consent/api/src/common" "github.com/bb-consent/api/src/config" + "github.com/bb-consent/api/src/token" "github.com/bb-consent/api/src/user" ) +type tokenResp struct { + AccessToken string `json:"accessToken"` + ExpiresIn int `json:"expiresIn"` + RefreshExpiresIn int `json:"refreshExpiresIn"` + RefreshToken string `json:"refreshToken"` + TokenType string `json:"tokenType"` +} + +type userLoginResp struct { + Individual user.UserV2 `json:"individual"` + Token tokenResp `json:"token"` +} + // LoginUser Implements the user login func LoginUser(w http.ResponseWriter, r *http.Request) { var lReq loginReq @@ -29,7 +43,7 @@ func LoginUser(w http.ResponseWriter, r *http.Request) { if !valid { log.Printf("Invalid request params for authentication") - common.HandleError(w, http.StatusBadRequest, err.Error(), err) + common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) return } @@ -43,27 +57,34 @@ func LoginUser(w http.ResponseWriter, r *http.Request) { return } m := fmt.Sprintf("Failed to get token for user:%v", lReq.Username) - common.HandleError(w, status, m, err) + common.HandleErrorV2(w, status, m, err) return } - sanitizedUserName := common.Sanitize(lReq.Username) - //TODO: Remove me when the auth server is per dev environment - u, err := user.GetByEmail(sanitizedUserName) + accessToken, err := token.ParseToken(t.AccessToken) if err != nil { - m := fmt.Sprintf("Login failed for non existant user:%v", lReq.Username) - common.HandleError(w, http.StatusUnauthorized, m, err) + m := fmt.Sprintf("Failed to parse token for user:%v", lReq.Username) + common.HandleErrorV2(w, status, m, err) return } - - if len(u.Roles) > 0 { - m := fmt.Sprintf("Login not allowed for admin users:%v", lReq.Username) - common.HandleError(w, http.StatusUnauthorized, m, err) + u, err := user.GetByIamIDV2(accessToken.IamID) + if err != nil { + m := fmt.Sprintf("User: %v does not exist", lReq.Username) + common.HandleErrorV2(w, status, m, err) return } + tResp := tokenResp{ + AccessToken: t.AccessToken, + ExpiresIn: t.ExpiresIn, + RefreshExpiresIn: t.RefreshExpiresIn, + RefreshToken: t.RefreshToken, + TokenType: t.TokenType, + } - resp, _ := json.Marshal(t) + lResp := userLoginResp{u, tResp} + resp, _ := json.Marshal(lResp) w.WriteHeader(http.StatusOK) w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) w.Write(resp) + } diff --git a/src/handlerv2/updateorganization_handler.go b/src/handlerv2/updateorganization_handler.go index 88bfa80..ed6a5c5 100644 --- a/src/handlerv2/updateorganization_handler.go +++ b/src/handlerv2/updateorganization_handler.go @@ -14,10 +14,10 @@ import ( ) type orgUpdateReq struct { - Name string - Location string - Description string - PolicyURL string + Name string `json:"name"` + Location string `json:"location"` + Description string `json:"description"` + PolicyURL string `json:"policyUrl"` } // UpdateOrganization Updates an organization @@ -33,7 +33,7 @@ func UpdateOrganization(w http.ResponseWriter, r *http.Request) { o, err := org.Get(organizationID) if err != nil { m := fmt.Sprintf("Failed to get organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } @@ -53,12 +53,9 @@ func UpdateOrganization(w http.ResponseWriter, r *http.Request) { orgResp, err := org.Update(o) if err != nil { m := fmt.Sprintf("Failed to update organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } go user.UpdateOrganizationsSubscribedUsers(orgResp) - //response, _ := json.Marshal(organization{orgResp}) - //w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) w.WriteHeader(http.StatusAccepted) - //w.Write(response) } diff --git a/src/handlerv2/updateorganizationcoverimage_handler.go b/src/handlerv2/updateorganizationcoverimage_handler.go index fe96b51..8f5abd8 100644 --- a/src/handlerv2/updateorganizationcoverimage_handler.go +++ b/src/handlerv2/updateorganizationcoverimage_handler.go @@ -13,6 +13,11 @@ import ( "github.com/bb-consent/api/src/org" ) +type coverImageResp struct { + CoverImageId string `json:"coverImageId"` + CoverImageUrl string `json:"coverImageUrl"` +} + // UpdateOrganizationCoverImage Inserts the image and update the id to user func UpdateOrganizationCoverImage(w http.ResponseWriter, r *http.Request) { organizationID := r.Header.Get(config.OrganizationId) @@ -20,7 +25,7 @@ func UpdateOrganizationCoverImage(w http.ResponseWriter, r *http.Request) { file, _, err := r.FormFile("orgimage") if err != nil { m := fmt.Sprintf("Failed to extract image organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } defer file.Close() @@ -29,14 +34,14 @@ func UpdateOrganizationCoverImage(w http.ResponseWriter, r *http.Request) { _, err = io.Copy(buf, file) if err != nil { m := fmt.Sprintf("Failed to copy image organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } imageID, err := image.Add(buf.Bytes()) if err != nil { m := fmt.Sprintf("Failed to store image in data store organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } @@ -44,11 +49,15 @@ func UpdateOrganizationCoverImage(w http.ResponseWriter, r *http.Request) { o, err := org.UpdateCoverImage(organizationID, imageID, imageURL) if err != nil { m := fmt.Sprintf("Failed to update organization: %v with image: %v details", organizationID, imageID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } + respBody := coverImageResp{ + CoverImageId: o.CoverImageID, + CoverImageUrl: o.CoverImageURL, + } - response, _ := json.Marshal(organization{o}) + response, _ := json.Marshal(respBody) w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) w.WriteHeader(http.StatusOK) w.Write(response) diff --git a/src/handlerv2/updateorganizationlogoimage_handler.go b/src/handlerv2/updateorganizationlogoimage_handler.go index fea8c86..1975850 100644 --- a/src/handlerv2/updateorganizationlogoimage_handler.go +++ b/src/handlerv2/updateorganizationlogoimage_handler.go @@ -13,6 +13,11 @@ import ( "github.com/bb-consent/api/src/org" ) +type logoImageResp struct { + LogoImageId string `json:"logoImageId"` + LogoImageUrl string `json:"logoImageUrl"` +} + // UpdateOrganizationLogoImage Inserts the image and update the id to user func UpdateOrganizationLogoImage(w http.ResponseWriter, r *http.Request) { organizationID := r.Header.Get(config.OrganizationId) @@ -20,7 +25,7 @@ func UpdateOrganizationLogoImage(w http.ResponseWriter, r *http.Request) { file, _, err := r.FormFile("orgimage") if err != nil { m := fmt.Sprintf("Failed to extract image organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } defer file.Close() @@ -29,14 +34,14 @@ func UpdateOrganizationLogoImage(w http.ResponseWriter, r *http.Request) { _, err = io.Copy(buf, file) if err != nil { m := fmt.Sprintf("Failed to copy image organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } imageID, err := image.Add(buf.Bytes()) if err != nil { m := fmt.Sprintf("Failed to store image in data store organization: %v", organizationID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } @@ -44,11 +49,16 @@ func UpdateOrganizationLogoImage(w http.ResponseWriter, r *http.Request) { o, err := org.UpdateLogoImage(organizationID, imageID, imageURL) if err != nil { m := fmt.Sprintf("Failed to update organization: %v with image: %v details", organizationID, imageID) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } - response, _ := json.Marshal(organization{o}) + respBody := logoImageResp{ + LogoImageId: o.LogoImageID, + LogoImageUrl: o.LogoImageURL, + } + + response, _ := json.Marshal(respBody) w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) w.WriteHeader(http.StatusOK) w.Write(response) diff --git a/src/handlerv2/validatephonenumber_handler.go b/src/handlerv2/validatephonenumber_handler.go index 4e2eff4..b248e22 100644 --- a/src/handlerv2/validatephonenumber_handler.go +++ b/src/handlerv2/validatephonenumber_handler.go @@ -17,7 +17,7 @@ import ( ) type validatePhoneNumberReq struct { - Phone string `valid:"required"` + Phone string `valid:"required" json:"phone"` } // ValidatePhoneNumber Check if the phone number is already in use @@ -32,7 +32,7 @@ func ValidatePhoneNumber(w http.ResponseWriter, r *http.Request) { valid, err := govalidator.ValidateStruct(validateReq) if valid != true { log.Printf("Missing mandatory params for validating phone number") - common.HandleError(w, http.StatusBadRequest, err.Error(), err) + common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) return } @@ -45,7 +45,7 @@ func ValidatePhoneNumber(w http.ResponseWriter, r *http.Request) { exist, err := user.PhoneNumberExist(sanitizedPhoneNumber) if err != nil { m := fmt.Sprintf("Failed to validate user phone number: %v", validateReq.Phone) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } @@ -63,7 +63,7 @@ func ValidatePhoneNumber(w http.ResponseWriter, r *http.Request) { o, err := otp.PhoneNumberExist(sanitizedPhoneNumber) if err != nil { m := fmt.Sprintf("Failed to validate user phone number: %v", validateReq.Phone) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } @@ -72,7 +72,7 @@ func ValidatePhoneNumber(w http.ResponseWriter, r *http.Request) { err = otp.Delete(o.ID.Hex()) if err != nil { m := fmt.Sprintf("Failed to clear expired otp") - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } } else { diff --git a/src/handlerv2/validateuseremail_handler.go b/src/handlerv2/validateuseremail_handler.go index b94e5a6..20b0336 100644 --- a/src/handlerv2/validateuseremail_handler.go +++ b/src/handlerv2/validateuseremail_handler.go @@ -17,8 +17,8 @@ type validateUserEmailReq struct { } type validateResp struct { - Result bool //True for valid email - Message string + Result bool `json:"result"` //True for valid email + Message string `json:"message"` } // ValidateUserEmail Validates the user email @@ -50,7 +50,7 @@ func ValidateUserEmail(w http.ResponseWriter, r *http.Request) { exist, err := user.EmailExist(sanitizedEmail) if err != nil { m := fmt.Sprintf("Failed to validate user email: %v", validateReq.Email) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } diff --git a/src/handlerv2/verifyotp_handler.go b/src/handlerv2/verifyotp_handler.go index 944055b..c6156d7 100644 --- a/src/handlerv2/verifyotp_handler.go +++ b/src/handlerv2/verifyotp_handler.go @@ -14,8 +14,8 @@ import ( ) type verifyOtpReq struct { - Phone string `valid:"required"` - Otp string `valid:"required"` + Phone string `valid:"required" json:"phone"` + Otp string `valid:"required" json:"otp"` } // VerifyOtp Verifies the Otp @@ -29,7 +29,7 @@ func VerifyOtp(w http.ResponseWriter, r *http.Request) { valid, err := govalidator.ValidateStruct(otpReq) if valid != true { log.Printf("Missing mandatory params for verify otp") - common.HandleError(w, http.StatusBadRequest, err.Error(), err) + common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) return } @@ -59,7 +59,7 @@ func VerifyOtp(w http.ResponseWriter, r *http.Request) { err := otp.UpdateVerified(o) if err != nil { m := fmt.Sprintf("Failed to update internal database") - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } } @@ -68,5 +68,4 @@ func VerifyOtp(w http.ResponseWriter, r *http.Request) { w.Header().Set(config.ContentTypeHeader, config.ContentTypeJSON) w.WriteHeader(http.StatusOK) w.Write(response) - return } diff --git a/src/handlerv2/verifyphonenumber_handler.go b/src/handlerv2/verifyphonenumber_handler.go index 835f052..ff94fda 100644 --- a/src/handlerv2/verifyphonenumber_handler.go +++ b/src/handlerv2/verifyphonenumber_handler.go @@ -19,9 +19,7 @@ import ( ) type verifyPhoneNumberReq struct { - Name string - Email string - Phone string `valid:"required"` + Phone string `valid:"required" json:"phone"` } // VerifyPhoneNumber Verifies the user phone number @@ -43,7 +41,7 @@ func generateVerificationCode() (code string, err error) { return string(b), nil } -func sendPhoneVerificationMessage(msgTo string, name string, message string) error { +func sendPhoneVerificationMessage(msgTo string, message string) error { urlStr := "https://api.twilio.com/2010-04-01/Accounts/" + twilioConfig.AccountSid + "/Messages.json" // Pack up the data for our message @@ -99,14 +97,14 @@ func verifyPhoneNumber(w http.ResponseWriter, r *http.Request, clientType int) { valid, err := govalidator.ValidateStruct(verifyReq) if valid != true { log.Printf("Invalid request params for verifying phone number") - common.HandleError(w, http.StatusBadRequest, err.Error(), err) + common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) return } vCode, err := generateVerificationCode() if err != nil { m := fmt.Sprintf("Failed to generate OTP :%v", verifyReq.Phone) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } @@ -118,15 +116,13 @@ func verifyPhoneNumber(w http.ResponseWriter, r *http.Request, clientType int) { fmt.Fprintf(&message, "Thank you for signing up for iGrant.io! Your code is %s", vCode) } - err = sendPhoneVerificationMessage(verifyReq.Phone, verifyReq.Name, message.String()) + err = sendPhoneVerificationMessage(verifyReq.Phone, message.String()) if err != nil { m := fmt.Sprintf("Failed to send sms to :%v", verifyReq.Phone) - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } - var o otp.Otp - o.Name = verifyReq.Name - o.Email = verifyReq.Email + var o otp.OtpV2 o.Phone = verifyReq.Phone o.Otp = vCode @@ -137,10 +133,10 @@ func verifyPhoneNumber(w http.ResponseWriter, r *http.Request, clientType int) { otp.Delete(oldOtp.ID.Hex()) } - o, err = otp.Add(o) + o, err = otp.AddV2(o) if err != nil { m := fmt.Sprintf("Failed to store otp details") - common.HandleError(w, http.StatusInternalServerError, m, err) + common.HandleErrorV2(w, http.StatusInternalServerError, m, err) return } w.WriteHeader(http.StatusNoContent) diff --git a/src/httppathsv2/routes.go b/src/httppathsv2/routes.go index 3a24b5f..69b8b40 100644 --- a/src/httppathsv2/routes.go +++ b/src/httppathsv2/routes.go @@ -107,7 +107,7 @@ func SetRoutes(r *mux.Router, e *casbin.Enforcer) { r.Handle(GetToken, http.HandlerFunc(handler.GetToken)).Methods("POST") r.Handle(GetOrganizationByID, m.Chain(handler.GetOrganizationByID, m.Logger(), m.Authorize(e), m.SetApplicationMode(), m.Authenticate())).Methods("GET") - r.Handle(UpdateOrganization, m.Chain(handler.UpdateOrganization, m.Logger(), m.Authorize(e), m.SetApplicationMode(), m.Authenticate())).Methods("POST") + r.Handle(UpdateOrganization, m.Chain(handler.UpdateOrganization, m.Logger(), m.Authorize(e), m.SetApplicationMode(), m.Authenticate())).Methods("PUT") r.Handle(UpdateOrganizationCoverImage, m.Chain(handler.UpdateOrganizationCoverImage, m.Logger(), m.Authorize(e), m.SetApplicationMode(), m.Authenticate())).Methods("POST") r.Handle(UpdateOrganizationLogoImage, m.Chain(handler.UpdateOrganizationLogoImage, m.Logger(), m.Authorize(e), m.SetApplicationMode(), m.Authenticate())).Methods("POST") r.Handle(GetOrganizationCoverImage, m.Chain(handler.GetOrganizationImage, m.Logger(), m.Authorize(e), m.SetApplicationMode(), m.Authenticate())).Methods("GET") diff --git a/src/otp/otps.go b/src/otp/otps.go index 130fc85..3ea5f50 100644 --- a/src/otp/otps.go +++ b/src/otp/otps.go @@ -18,6 +18,12 @@ type Otp struct { Otp string Verified bool } +type OtpV2 struct { + ID primitive.ObjectID `bson:"_id,omitempty"` + Phone string + Otp string + Verified bool +} func collection() *mongo.Collection { return database.DB.Client.Database(database.DB.Name).Collection("otps") @@ -36,6 +42,19 @@ func Add(otp Otp) (Otp, error) { return otp, nil } +// Add Adds the otp to the db +func AddV2(otp OtpV2) (OtpV2, error) { + + otp.ID = primitive.NewObjectID() + + _, err := collection().InsertOne(context.TODO(), otp) + if err != nil { + return OtpV2{}, err + } + + return otp, nil +} + // Delete Deletes the otp entry by ID func Delete(otpID string) error { otpId, err := primitive.ObjectIDFromHex(otpID) diff --git a/src/user/users.go b/src/user/users.go index 76901df..f246e68 100644 --- a/src/user/users.go +++ b/src/user/users.go @@ -25,41 +25,59 @@ import ( // Org Organization snippet stored as part of user type Org struct { - OrgID primitive.ObjectID `bson:"orgid,omitempty"` - Name string - Location string - Type string - TypeID primitive.ObjectID `bson:"typeid,omitempty"` - EulaAccepted bool + OrgID primitive.ObjectID `bson:"orgid,omitempty" json:"id"` + Name string `json:"name"` + Location string `json:"location"` + Type string `json:"type"` + TypeID primitive.ObjectID `bson:"typeid,omitempty" json:"typeId"` + EulaAccepted bool `json:"lastVisit"` } // ClientInfo The client device details. type ClientInfo struct { - Token string - Type int + Token string `json:"token"` + Type int `json:"type"` } // Role Role assignment to user type Role struct { - RoleID int - OrgID string + RoleID int `json:"roleId"` + OrgID string `json:"orgId"` } // User data type type User struct { - ID primitive.ObjectID `bson:"_id,omitempty"` - Name string - IamID string - Email string - Phone string - ImageID string - ImageURL string - LastVisit string //TODO Replace with ISODate() - Client ClientInfo - Orgs []Org - APIKey string - Roles []Role - IncompleteProfile bool + ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` + Name string `json:"name"` + IamID string `json:"iamId"` + Email string `json:"email"` + Phone string `json:"phone"` + ImageID string `json:"imageId"` + ImageURL string `json:"imageUrl"` + LastVisit string `json:"lastVisit"` //TODO Replace with ISODate() + Client ClientInfo `json:"client"` + Orgs []Org `json:"orgs"` + APIKey string `json:"apiKey"` + Roles []Role `json:"roles"` + IncompleteProfile bool `json:"incompleteProfile"` +} + +type UserV2 struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` + Name string `json:"name"` + ExternalId string `json:"externalId"` + ExternalIdType string `json:"externalIdType"` + IdentityProviderId string `json:"identityProviderId"` + IamID string `json:"iamId"` + Email string `json:"email"` + Phone string `json:"phone"` + ImageID string `json:"imageId"` + ImageURL string `json:"imageUrl"` + LastVisit string `json:"lastVisit"` //TODO Replace with ISODate() + Orgs []Org `json:"orgs"` + APIKey string `json:"apiKey"` + Roles []Role `json:"roles"` + IncompleteProfile bool `json:"incompleteProfile"` } func collection() *mongo.Collection { @@ -119,6 +137,18 @@ func GetByIamID(iamID string) (User, error) { return result, err } +func GetByIamIDV2(iamID string) (UserV2, error) { + var result UserV2 + + err := collection().FindOne(context.TODO(), bson.M{"iamid": iamID}).Decode(&result) + if err != nil { + log.Printf("Failed to find user id:%v err:%v", iamID, err) + return result, err + } + + return result, err +} + // Get Gets a single user by given id func Get(userID string) (User, error) { c := collection()