diff --git a/internal/handler/v2/onboard/onboard_reset_password.go b/internal/handler/v2/onboard/onboard_reset_password.go index 6057fa2..cfa25c1 100644 --- a/internal/handler/v2/onboard/onboard_reset_password.go +++ b/internal/handler/v2/onboard/onboard_reset_password.go @@ -2,6 +2,7 @@ package onboard import ( "encoding/json" + "fmt" "io/ioutil" "log" "net/http" @@ -11,6 +12,7 @@ import ( "github.com/bb-consent/api/internal/config" "github.com/bb-consent/api/internal/iam" "github.com/bb-consent/api/internal/token" + "github.com/bb-consent/api/internal/user" ) type resetPasswordReq struct { @@ -32,10 +34,20 @@ func OnboardResetPassword(w http.ResponseWriter, r *http.Request) { common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) return } - err = iam.ResetPassword(userIamID, resetReq.NewPassword) + + // fetch the current user + user, err := user.GetByIamID(userIamID) if err != nil { - log.Printf("Failed to reset user:%v password ") - common.HandleErrorV2(w, http.StatusBadRequest, err.Error(), err) + m := "Failed to fetch user" + common.HandleErrorV2(w, http.StatusBadRequest, m, err) + return + } + + // reset user password + err = iam.ResetPassword(userIamID, user.Email, resetReq.CurrentPassword, resetReq.NewPassword) + if err != nil { + m := fmt.Sprintf("Failed to reset user:%v password", userIamID) + common.HandleErrorV2(w, http.StatusBadRequest, m, err) return } diff --git a/internal/iam/iam.go b/internal/iam/iam.go index 97812e6..aea73c3 100644 --- a/internal/iam/iam.go +++ b/internal/iam/iam.go @@ -105,15 +105,23 @@ type IamError struct { Error string `json:"error_description"` } -func ResetPassword(userId string, password string) error { +func ResetPassword(userId string, username string, currentPassword string, newPassword string) error { client := GetClient() + ctx := context.Background() + clientId := IamConfig.ClientId + grantType := "password" + _, err := client.GetToken(ctx, IamConfig.Realm, gocloak.TokenOptions{Username: &username, Password: ¤tPassword, ClientID: &clientId, GrantType: &grantType}) + if err != nil { + return err + } + token, err := GetAdminToken(IamConfig.AdminUser, IamConfig.AdminPassword, "master", client) if err != nil { return err } - err = client.SetPassword(context.Background(), token.AccessToken, userId, IamConfig.Realm, password, false) + err = client.SetPassword(context.Background(), token.AccessToken, userId, IamConfig.Realm, newPassword, false) return err }