|
4 | 4 | "bufio"
|
5 | 5 | "fmt"
|
6 | 6 | "os"
|
| 7 | + "path/filepath" |
7 | 8 | "strings"
|
8 | 9 | "sync"
|
9 | 10 |
|
@@ -110,10 +111,7 @@ func (hc *HtpasswdClient) ChangePassword(login, supposedOldPassword, newPassword
|
110 | 111 | return zerr.ErrPasswordIsEmpty
|
111 | 112 | }
|
112 | 113 |
|
113 |
| - hc.credMap.rw.RLock() |
114 |
| - oldPassphrase, ok := hc.credMap.m[login] |
115 |
| - hc.credMap.rw.RUnlock() |
116 |
| - |
| 114 | + oldPassphrase, ok := hc.credMap.Get(login) |
117 | 115 | if !ok {
|
118 | 116 | return zerr.ErrBadUser
|
119 | 117 | }
|
@@ -151,10 +149,31 @@ func (hc *HtpasswdClient) ChangePassword(login, supposedOldPassword, newPassword
|
151 | 149 | }
|
152 | 150 | }
|
153 | 151 |
|
154 |
| - // write new content to file |
155 |
| - output := strings.Join(lines, "\n") |
| 152 | + // write new content to temporary file |
| 153 | + // and replace the old file with temporary, so the operation is atomic |
| 154 | + output := []byte(strings.Join(lines, "\n")) |
| 155 | + |
| 156 | + tmpfile, err := os.CreateTemp(filepath.Dir(hc.filepath), "htpasswd-*.tmp") |
| 157 | + if err != nil { |
| 158 | + return fmt.Errorf("error occurred when creating temp htpasswd file: %w", err) |
| 159 | + } |
| 160 | + |
| 161 | + if _, err := tmpfile.Write(output); err != nil { |
| 162 | + tmpfile.Close() |
| 163 | + os.Remove(tmpfile.Name()) |
| 164 | + return fmt.Errorf("error occurred when writing to temp htpasswd file: %w", err) |
| 165 | + } |
| 166 | + |
| 167 | + if err := tmpfile.Close(); err != nil { |
| 168 | + os.Remove(tmpfile.Name()) |
| 169 | + return fmt.Errorf("error occurred when closing temp htpasswd file: %w", err) |
| 170 | + } |
| 171 | + |
| 172 | + if err := os.Rename(tmpfile.Name(), hc.filepath); err != nil { |
| 173 | + return fmt.Errorf("error occurred while replacing htpasswd file with new file: %w", err) |
| 174 | + } |
156 | 175 |
|
157 |
| - err = os.WriteFile(hc.filepath, []byte(output), constants.DefaultDirPerms) |
| 176 | + err = os.WriteFile(hc.filepath, output, constants.DefaultDirPerms) |
158 | 177 | if err != nil {
|
159 | 178 | return fmt.Errorf("error occurred while writing to creds-file: %w", err)
|
160 | 179 | }
|
|
0 commit comments