| 49 | } |
| 50 | |
| 51 | func UpdateConfigWithNewJWTKey(jwtKey string) error { |
| 52 | file, err := os.Open("./config.yml") |
| 53 | if err != nil { |
| 54 | return fmt.Errorf("can't open config.yml: %w", err) |
| 55 | } |
| 56 | defer file.Close() |
| 57 | |
| 58 | var lines []string |
| 59 | scanner := bufio.NewScanner(file) |
| 60 | secretUpdated := false |
| 61 | |
| 62 | for scanner.Scan() { |
| 63 | line := scanner.Text() |
| 64 | |
| 65 | if strings.HasPrefix(strings.TrimSpace(line), "secret_jwt_key:") { |
| 66 | whitespace := "" |
| 67 | for _, char := range line { |
| 68 | if char != ' ' && char != '\t' { |
| 69 | break |
| 70 | } |
| 71 | whitespace += string(char) |
| 72 | } |
| 73 | |
| 74 | lines = append(lines, fmt.Sprintf(`%ssecret_jwt_key: "%s"`, whitespace, jwtKey)) |
| 75 | secretUpdated = true |
| 76 | } else { |
| 77 | lines = append(lines, line) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | if err := scanner.Err(); err != nil { |
| 82 | return fmt.Errorf("config read error: %w", err) |
| 83 | } |
| 84 | |
| 85 | if !secretUpdated { |
| 86 | lines = append(lines, fmt.Sprintf(`secret_jwt_key: "%s"`, jwtKey)) |
| 87 | } |
| 88 | |
| 89 | content := strings.Join(lines, "\n") |
| 90 | err = os.WriteFile("./config.yml", []byte(content), 0644) |
| 91 | if err != nil { |
| 92 | return fmt.Errorf("config write error: %w", err) |
| 93 | } |
| 94 | |
| 95 | return nil |
| 96 | } |