hazo_auth 4.2.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/bin/hazo_auth.mjs +35 -0
  2. package/cli-src/assets/images/forgot_password_default.jpg +0 -0
  3. package/cli-src/assets/images/login_default.jpg +0 -0
  4. package/cli-src/assets/images/register_default.jpg +0 -0
  5. package/cli-src/assets/images/reset_password_default.jpg +0 -0
  6. package/cli-src/assets/images/verify_email_default.jpg +0 -0
  7. package/cli-src/cli/generate.ts +276 -0
  8. package/cli-src/cli/index.ts +207 -0
  9. package/cli-src/cli/init.ts +254 -0
  10. package/cli-src/cli/init_users.ts +376 -0
  11. package/cli-src/cli/validate.ts +581 -0
  12. package/cli-src/lib/already_logged_in_config.server.ts +46 -0
  13. package/cli-src/lib/app_logger.ts +24 -0
  14. package/cli-src/lib/auth/auth_cache.ts +220 -0
  15. package/cli-src/lib/auth/auth_rate_limiter.ts +121 -0
  16. package/cli-src/lib/auth/auth_types.ts +117 -0
  17. package/cli-src/lib/auth/auth_utils.server.ts +196 -0
  18. package/cli-src/lib/auth/dev_lock_validator.edge.ts +171 -0
  19. package/cli-src/lib/auth/hazo_get_auth.server.ts +583 -0
  20. package/cli-src/lib/auth/index.ts +23 -0
  21. package/cli-src/lib/auth/nextauth_config.ts +227 -0
  22. package/cli-src/lib/auth/org_cache.ts +148 -0
  23. package/cli-src/lib/auth/scope_cache.ts +233 -0
  24. package/cli-src/lib/auth/server_auth.ts +88 -0
  25. package/cli-src/lib/auth/session_token_validator.edge.ts +92 -0
  26. package/cli-src/lib/auth_utility_config.server.ts +136 -0
  27. package/cli-src/lib/config/config_loader.server.ts +164 -0
  28. package/cli-src/lib/config/default_config.ts +243 -0
  29. package/cli-src/lib/dev_lock_config.server.ts +148 -0
  30. package/cli-src/lib/email_verification_config.server.ts +63 -0
  31. package/cli-src/lib/file_types_config.server.ts +25 -0
  32. package/cli-src/lib/forgot_password_config.server.ts +63 -0
  33. package/cli-src/lib/hazo_connect_instance.server.ts +101 -0
  34. package/cli-src/lib/hazo_connect_setup.server.ts +194 -0
  35. package/cli-src/lib/hazo_connect_setup.ts +54 -0
  36. package/cli-src/lib/index.ts +46 -0
  37. package/cli-src/lib/login_config.server.ts +106 -0
  38. package/cli-src/lib/messages_config.server.ts +45 -0
  39. package/cli-src/lib/migrations/apply_migration.ts +105 -0
  40. package/cli-src/lib/multi_tenancy_config.server.ts +94 -0
  41. package/cli-src/lib/my_settings_config.server.ts +135 -0
  42. package/cli-src/lib/oauth_config.server.ts +87 -0
  43. package/cli-src/lib/password_requirements_config.server.ts +40 -0
  44. package/cli-src/lib/profile_pic_menu_config.server.ts +138 -0
  45. package/cli-src/lib/profile_picture_config.server.ts +56 -0
  46. package/cli-src/lib/register_config.server.ts +101 -0
  47. package/cli-src/lib/reset_password_config.server.ts +103 -0
  48. package/cli-src/lib/scope_hierarchy_config.server.ts +151 -0
  49. package/cli-src/lib/services/email_service.ts +587 -0
  50. package/cli-src/lib/services/email_verification_service.ts +270 -0
  51. package/cli-src/lib/services/index.ts +16 -0
  52. package/cli-src/lib/services/login_service.ts +150 -0
  53. package/cli-src/lib/services/oauth_service.ts +494 -0
  54. package/cli-src/lib/services/org_service.ts +965 -0
  55. package/cli-src/lib/services/password_change_service.ts +154 -0
  56. package/cli-src/lib/services/password_reset_service.ts +418 -0
  57. package/cli-src/lib/services/profile_picture_remove_service.ts +120 -0
  58. package/cli-src/lib/services/profile_picture_service.ts +451 -0
  59. package/cli-src/lib/services/profile_picture_source_mapper.ts +62 -0
  60. package/cli-src/lib/services/registration_service.ts +185 -0
  61. package/cli-src/lib/services/scope_labels_service.ts +348 -0
  62. package/cli-src/lib/services/scope_service.ts +778 -0
  63. package/cli-src/lib/services/session_token_service.ts +178 -0
  64. package/cli-src/lib/services/token_service.ts +240 -0
  65. package/cli-src/lib/services/user_profiles_cache.ts +189 -0
  66. package/cli-src/lib/services/user_profiles_service.ts +264 -0
  67. package/cli-src/lib/services/user_scope_service.ts +554 -0
  68. package/cli-src/lib/services/user_update_service.ts +141 -0
  69. package/cli-src/lib/ui_shell_config.server.ts +73 -0
  70. package/cli-src/lib/ui_sizes_config.server.ts +37 -0
  71. package/cli-src/lib/user_fields_config.server.ts +31 -0
  72. package/cli-src/lib/user_management_config.server.ts +39 -0
  73. package/cli-src/lib/user_profiles_config.server.ts +55 -0
  74. package/cli-src/lib/utils/api_route_helpers.ts +60 -0
  75. package/cli-src/lib/utils/error_sanitizer.ts +75 -0
  76. package/cli-src/lib/utils/password_validator.ts +65 -0
  77. package/cli-src/lib/utils.ts +11 -0
  78. package/cli-src/server/logging/logger_service.ts +56 -0
  79. package/cli-src/server/types/app_types.ts +74 -0
  80. package/cli-src/server/types/express.d.ts +16 -0
  81. package/dist/cli/index.js +18 -0
  82. package/dist/cli/init_users.d.ts +17 -0
  83. package/dist/cli/init_users.d.ts.map +1 -0
  84. package/dist/cli/init_users.js +307 -0
  85. package/dist/components/layouts/dev_lock/index.d.ts +29 -0
  86. package/dist/components/layouts/dev_lock/index.d.ts.map +1 -0
  87. package/dist/components/layouts/dev_lock/index.js +60 -0
  88. package/dist/components/layouts/index.d.ts +2 -0
  89. package/dist/components/layouts/index.d.ts.map +1 -1
  90. package/dist/components/layouts/index.js +1 -0
  91. package/dist/components/layouts/org_management/index.d.ts +26 -0
  92. package/dist/components/layouts/org_management/index.d.ts.map +1 -0
  93. package/dist/components/layouts/org_management/index.js +75 -0
  94. package/dist/components/layouts/shared/config/layout_customization.d.ts +2 -7
  95. package/dist/components/layouts/shared/config/layout_customization.d.ts.map +1 -1
  96. package/dist/components/layouts/user_management/components/org_hierarchy_tab.d.ts +13 -0
  97. package/dist/components/layouts/user_management/components/org_hierarchy_tab.d.ts.map +1 -0
  98. package/dist/components/layouts/user_management/components/org_hierarchy_tab.js +276 -0
  99. package/dist/components/layouts/user_management/index.d.ts +3 -1
  100. package/dist/components/layouts/user_management/index.d.ts.map +1 -1
  101. package/dist/components/layouts/user_management/index.js +10 -4
  102. package/dist/lib/auth/auth_types.d.ts +6 -0
  103. package/dist/lib/auth/auth_types.d.ts.map +1 -1
  104. package/dist/lib/auth/dev_lock_validator.edge.d.ts +38 -0
  105. package/dist/lib/auth/dev_lock_validator.edge.d.ts.map +1 -0
  106. package/dist/lib/auth/dev_lock_validator.edge.js +122 -0
  107. package/dist/lib/auth/hazo_get_auth.server.d.ts.map +1 -1
  108. package/dist/lib/auth/hazo_get_auth.server.js +61 -1
  109. package/dist/lib/auth/org_cache.d.ts +65 -0
  110. package/dist/lib/auth/org_cache.d.ts.map +1 -0
  111. package/dist/lib/auth/org_cache.js +103 -0
  112. package/dist/lib/config/default_config.d.ts +76 -0
  113. package/dist/lib/config/default_config.d.ts.map +1 -1
  114. package/dist/lib/config/default_config.js +42 -0
  115. package/dist/lib/dev_lock_config.server.d.ts +41 -0
  116. package/dist/lib/dev_lock_config.server.d.ts.map +1 -0
  117. package/dist/lib/dev_lock_config.server.js +50 -0
  118. package/dist/lib/multi_tenancy_config.server.d.ts +30 -0
  119. package/dist/lib/multi_tenancy_config.server.d.ts.map +1 -0
  120. package/dist/lib/multi_tenancy_config.server.js +41 -0
  121. package/dist/lib/services/org_service.d.ts +191 -0
  122. package/dist/lib/services/org_service.d.ts.map +1 -0
  123. package/dist/lib/services/org_service.js +746 -0
  124. package/dist/lib/utils/password_validator.d.ts +7 -1
  125. package/dist/lib/utils/password_validator.d.ts.map +1 -1
  126. package/dist/page_components/dev_lock.d.ts +11 -0
  127. package/dist/page_components/dev_lock.d.ts.map +1 -0
  128. package/dist/page_components/dev_lock.js +17 -0
  129. package/dist/page_components/index.d.ts +1 -0
  130. package/dist/page_components/index.d.ts.map +1 -1
  131. package/dist/page_components/index.js +1 -0
  132. package/dist/page_components/org_management.d.ts +27 -0
  133. package/dist/page_components/org_management.d.ts.map +1 -0
  134. package/dist/page_components/org_management.js +18 -0
  135. package/hazo_auth_config.example.ini +30 -0
  136. package/package.json +27 -3
@@ -0,0 +1,154 @@
1
+ // file_description: service for changing user password using hazo_connect
2
+ // section: imports
3
+ import type { HazoConnectAdapter } from "hazo_connect";
4
+ import { createCrudService } from "hazo_connect/server";
5
+ import argon2 from "argon2";
6
+ import { get_password_requirements_config } from "../password_requirements_config.server.js";
7
+ import { send_template_email } from "./email_service.js";
8
+ import { create_app_logger } from "../app_logger.js";
9
+
10
+ // section: types
11
+ export type PasswordChangeData = {
12
+ current_password: string;
13
+ new_password: string;
14
+ };
15
+
16
+ export type PasswordChangeResult = {
17
+ success: boolean;
18
+ error?: string;
19
+ };
20
+
21
+ // section: helpers
22
+ /**
23
+ * Changes a user's password
24
+ * Verifies the current password, validates the new password, and updates the password hash
25
+ * @param adapter - The hazo_connect adapter instance
26
+ * @param user_id - The user ID to update
27
+ * @param data - Password change data (current_password, new_password)
28
+ * @returns Password change result with success status or error
29
+ */
30
+ export async function change_password(
31
+ adapter: HazoConnectAdapter,
32
+ user_id: string,
33
+ data: PasswordChangeData,
34
+ ): Promise<PasswordChangeResult> {
35
+ try {
36
+ const { current_password, new_password } = data;
37
+
38
+ // Create CRUD service for hazo_users table
39
+ const users_service = createCrudService(adapter, "hazo_users");
40
+
41
+ // Get current user data
42
+ const users = await users_service.findBy({
43
+ id: user_id,
44
+ });
45
+
46
+ if (!Array.isArray(users) || users.length === 0) {
47
+ return {
48
+ success: false,
49
+ error: "User not found",
50
+ };
51
+ }
52
+
53
+ const user = users[0];
54
+ const password_hash = user.password_hash as string;
55
+ const email = user.email_address as string;
56
+ const user_name = user.name as string | undefined;
57
+
58
+ // Verify current password
59
+ try {
60
+ const is_valid = await argon2.verify(password_hash, current_password);
61
+ if (!is_valid) {
62
+ return {
63
+ success: false,
64
+ error: "Current password is incorrect",
65
+ };
66
+ }
67
+ } catch (error) {
68
+ return {
69
+ success: false,
70
+ error: "Failed to verify current password",
71
+ };
72
+ }
73
+
74
+ // Get password requirements from config
75
+ const password_requirements = get_password_requirements_config();
76
+
77
+ // Validate new password
78
+ if (!new_password || new_password.length < password_requirements.minimum_length) {
79
+ return {
80
+ success: false,
81
+ error: `Password must be at least ${password_requirements.minimum_length} characters long`,
82
+ };
83
+ }
84
+
85
+ if (password_requirements.require_uppercase && !/[A-Z]/.test(new_password)) {
86
+ return {
87
+ success: false,
88
+ error: "Password must contain at least one uppercase letter",
89
+ };
90
+ }
91
+
92
+ if (password_requirements.require_lowercase && !/[a-z]/.test(new_password)) {
93
+ return {
94
+ success: false,
95
+ error: "Password must contain at least one lowercase letter",
96
+ };
97
+ }
98
+
99
+ if (password_requirements.require_number && !/[0-9]/.test(new_password)) {
100
+ return {
101
+ success: false,
102
+ error: "Password must contain at least one number",
103
+ };
104
+ }
105
+
106
+ if (password_requirements.require_special && !/[^A-Za-z0-9]/.test(new_password)) {
107
+ return {
108
+ success: false,
109
+ error: "Password must contain at least one special character",
110
+ };
111
+ }
112
+
113
+ // Hash the new password
114
+ const new_password_hash = await argon2.hash(new_password);
115
+
116
+ // Update password hash in database
117
+ const now = new Date().toISOString();
118
+ await users_service.updateById(user_id, {
119
+ password_hash: new_password_hash,
120
+ changed_at: now,
121
+ });
122
+
123
+ // Send password changed notification email
124
+ const email_result = await send_template_email("password_changed", email, {
125
+ user_email: email,
126
+ user_name: user_name,
127
+ });
128
+
129
+ if (!email_result.success) {
130
+ const logger = create_app_logger();
131
+ logger.error("password_change_service_email_failed", {
132
+ filename: "password_change_service.ts",
133
+ line_number: 0,
134
+ user_id,
135
+ email,
136
+ error: email_result.error,
137
+ note: "Password was changed successfully but notification email failed to send",
138
+ });
139
+ }
140
+
141
+ return {
142
+ success: true,
143
+ };
144
+ } catch (error) {
145
+ const error_message =
146
+ error instanceof Error ? error.message : "Unknown error";
147
+
148
+ return {
149
+ success: false,
150
+ error: error_message,
151
+ };
152
+ }
153
+ }
154
+
@@ -0,0 +1,418 @@
1
+ // file_description: service for password reset operations using hazo_connect
2
+ // section: imports
3
+ import type { HazoConnectAdapter } from "hazo_connect";
4
+ import { createCrudService } from "hazo_connect/server";
5
+ import { create_token } from "./token_service.js";
6
+ import argon2 from "argon2";
7
+ import { create_app_logger } from "../app_logger.js";
8
+ import { send_template_email } from "./email_service.js";
9
+
10
+ // section: types
11
+ export type PasswordResetRequestData = {
12
+ email: string;
13
+ };
14
+
15
+ export type PasswordResetRequestResult = {
16
+ success: boolean;
17
+ error?: string;
18
+ /** True if the user doesn't have a password set (Google-only user) */
19
+ no_password_set?: boolean;
20
+ };
21
+
22
+ export type PasswordResetData = {
23
+ token: string;
24
+ new_password: string;
25
+ minimum_length?: number; // Optional: if not provided, defaults to 8
26
+ };
27
+
28
+ export type PasswordResetResult = {
29
+ success: boolean;
30
+ user_id?: string;
31
+ email?: string;
32
+ error?: string;
33
+ };
34
+
35
+ export type PasswordResetTokenValidationData = {
36
+ token: string;
37
+ };
38
+
39
+ export type PasswordResetTokenValidationResult = {
40
+ success: boolean;
41
+ error?: string;
42
+ };
43
+
44
+ // section: helpers
45
+ /**
46
+ * Requests a password reset for a user by email
47
+ * Generates a secure token, hashes it, and stores it in hazo_refresh_tokens with token_type = 'password_reset'
48
+ * Invalidates any existing password reset tokens for the user before creating a new one
49
+ * @param adapter - The hazo_connect adapter instance
50
+ * @param data - Password reset request data (email)
51
+ * @returns Password reset request result with success status or error
52
+ */
53
+ export async function request_password_reset(
54
+ adapter: HazoConnectAdapter,
55
+ data: PasswordResetRequestData,
56
+ ): Promise<PasswordResetRequestResult> {
57
+ try {
58
+ const { email } = data;
59
+
60
+ // Create CRUD service for hazo_users table
61
+ const users_service = createCrudService(adapter, "hazo_users");
62
+
63
+ // Find user by email
64
+ const users = await users_service.findBy({
65
+ email_address: email,
66
+ });
67
+
68
+ // If user not found, return success anyway (to prevent email enumeration)
69
+ if (!Array.isArray(users) || users.length === 0) {
70
+ return {
71
+ success: true,
72
+ };
73
+ }
74
+
75
+ const user = users[0];
76
+ const user_id = user.id as string;
77
+
78
+ // Check if user has a password set (Google-only users don't have a password)
79
+ const password_hash = user.password_hash as string;
80
+ if (!password_hash || password_hash === "") {
81
+ // User doesn't have a password - they need to set one via My Settings after logging in with Google
82
+ // Return success to prevent email enumeration, but include flag for UI handling
83
+ return {
84
+ success: true,
85
+ no_password_set: true,
86
+ };
87
+ }
88
+
89
+ // Create password reset token using shared token service
90
+ const token_result = await create_token({
91
+ adapter,
92
+ user_id,
93
+ token_type: "password_reset",
94
+ });
95
+
96
+ if (!token_result.success) {
97
+ return {
98
+ success: false,
99
+ error: token_result.error || "Failed to create password reset token",
100
+ };
101
+ }
102
+
103
+ // Send password reset email if token was created successfully
104
+ if (token_result.raw_token) {
105
+ const email_result = await send_template_email("forgot_password", email, {
106
+ token: token_result.raw_token,
107
+ user_email: email,
108
+ user_name: user.name as string | undefined,
109
+ });
110
+
111
+ if (!email_result.success) {
112
+ const logger = create_app_logger();
113
+ logger.error("password_reset_service_email_send_failed", {
114
+ filename: "password_reset_service.ts",
115
+ line_number: 0,
116
+ user_id,
117
+ email,
118
+ error: email_result.error,
119
+ note: "Password reset token created but email failed to send",
120
+ });
121
+ }
122
+ }
123
+
124
+ return {
125
+ success: true,
126
+ };
127
+ } catch (error) {
128
+ const error_message =
129
+ error instanceof Error ? error.message : "Unknown error";
130
+
131
+ return {
132
+ success: false,
133
+ error: error_message,
134
+ };
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Validates a password reset token without resetting the password
140
+ * Verifies the token exists and checks if it has expired
141
+ * @param adapter - The hazo_connect adapter instance
142
+ * @param data - Token validation data (token)
143
+ * @returns Token validation result with success status or error
144
+ */
145
+ export async function validate_password_reset_token(
146
+ adapter: HazoConnectAdapter,
147
+ data: PasswordResetTokenValidationData,
148
+ ): Promise<PasswordResetTokenValidationResult> {
149
+ try {
150
+ const { token } = data;
151
+
152
+ // Create CRUD service for hazo_refresh_tokens table
153
+ const tokens_service = createCrudService(adapter, "hazo_refresh_tokens");
154
+
155
+ // Find all password reset tokens
156
+ // If token_type column doesn't exist, query all tokens and filter manually
157
+ let all_tokens: unknown[] = [];
158
+ try {
159
+ all_tokens = (await tokens_service.findBy({
160
+ token_type: "password_reset",
161
+ })) as unknown[];
162
+ } catch (error) {
163
+ // If token_type column doesn't exist, get all tokens and we'll verify each one
164
+ const logger = create_app_logger();
165
+ const error_message = error instanceof Error ? error.message : "Unknown error";
166
+ logger.warn("password_reset_service_token_type_column_missing", {
167
+ filename: "password_reset_service.ts",
168
+ line_number: 0,
169
+ error: error_message,
170
+ note: "token_type column may not exist, querying all tokens",
171
+ });
172
+ try {
173
+ // Query all tokens (will need to verify each one)
174
+ all_tokens = (await tokens_service.findBy({})) as unknown[];
175
+ } catch (fallbackError) {
176
+ const fallback_error_message = fallbackError instanceof Error ? fallbackError.message : "Unknown error";
177
+ logger.error("password_reset_service_query_tokens_failed", {
178
+ filename: "password_reset_service.ts",
179
+ line_number: 0,
180
+ error: fallback_error_message,
181
+ });
182
+ return {
183
+ success: false,
184
+ error: "Invalid or expired reset token",
185
+ };
186
+ }
187
+ }
188
+
189
+ if (!Array.isArray(all_tokens) || all_tokens.length === 0) {
190
+ return {
191
+ success: false,
192
+ error: "Invalid or expired reset token",
193
+ };
194
+ }
195
+
196
+ // Find the matching token by verifying the hash
197
+ let matching_token = null;
198
+
199
+ for (const stored_token of all_tokens) {
200
+ try {
201
+ const token_hash = (stored_token as { token_hash: string }).token_hash;
202
+ const is_valid = await argon2.verify(token_hash, token);
203
+
204
+ if (is_valid) {
205
+ matching_token = stored_token;
206
+ break;
207
+ }
208
+ } catch {
209
+ // Continue to next token if verification fails
210
+ continue;
211
+ }
212
+ }
213
+
214
+ if (!matching_token) {
215
+ return {
216
+ success: false,
217
+ error: "Invalid or expired reset token",
218
+ };
219
+ }
220
+
221
+ // Check if token has expired
222
+ const expires_at = new Date((matching_token as { expires_at: string }).expires_at);
223
+ const now = new Date();
224
+
225
+ if (expires_at < now) {
226
+ return {
227
+ success: false,
228
+ error: "Reset token has expired",
229
+ };
230
+ }
231
+
232
+ return {
233
+ success: true,
234
+ };
235
+ } catch (error) {
236
+ const error_message =
237
+ error instanceof Error ? error.message : "Unknown error";
238
+
239
+ return {
240
+ success: false,
241
+ error: error_message,
242
+ };
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Resets a user's password using a password reset token
248
+ * Verifies the token, checks expiration, updates password, and deletes the token
249
+ * @param adapter - The hazo_connect adapter instance
250
+ * @param data - Password reset data (token, new_password)
251
+ * @returns Password reset result with success status, user_id, email, or error
252
+ */
253
+ export async function reset_password(
254
+ adapter: HazoConnectAdapter,
255
+ data: PasswordResetData,
256
+ ): Promise<PasswordResetResult> {
257
+ try {
258
+ const { token, new_password, minimum_length = 8 } = data;
259
+
260
+ // Validate password
261
+ if (!new_password || new_password.length < minimum_length) {
262
+ return {
263
+ success: false,
264
+ error: `Password must be at least ${minimum_length} character${minimum_length === 1 ? "" : "s"} long`,
265
+ };
266
+ }
267
+
268
+ // Create CRUD service for hazo_refresh_tokens table
269
+ const tokens_service = createCrudService(adapter, "hazo_refresh_tokens");
270
+
271
+ // Find all password reset tokens
272
+ // If token_type column doesn't exist, query all tokens and filter manually
273
+ let all_tokens: unknown[] = [];
274
+ try {
275
+ all_tokens = (await tokens_service.findBy({
276
+ token_type: "password_reset",
277
+ })) as unknown[];
278
+ } catch (error) {
279
+ // If token_type column doesn't exist, get all tokens and we'll verify each one
280
+ const logger = create_app_logger();
281
+ const error_message = error instanceof Error ? error.message : "Unknown error";
282
+ logger.warn("password_reset_service_token_type_column_missing", {
283
+ filename: "password_reset_service.ts",
284
+ line_number: 0,
285
+ error: error_message,
286
+ note: "token_type column may not exist, querying all tokens",
287
+ });
288
+ try {
289
+ // Query all tokens (will need to verify each one)
290
+ all_tokens = (await tokens_service.findBy({})) as unknown[];
291
+ } catch (fallbackError) {
292
+ const fallback_error_message = fallbackError instanceof Error ? fallbackError.message : "Unknown error";
293
+ logger.error("password_reset_service_query_tokens_failed", {
294
+ filename: "password_reset_service.ts",
295
+ line_number: 0,
296
+ error: fallback_error_message,
297
+ });
298
+ return {
299
+ success: false,
300
+ error: "Invalid or expired reset token",
301
+ };
302
+ }
303
+ }
304
+
305
+ if (!Array.isArray(all_tokens) || all_tokens.length === 0) {
306
+ return {
307
+ success: false,
308
+ error: "Invalid or expired reset token",
309
+ };
310
+ }
311
+
312
+ // Find the matching token by verifying the hash
313
+ let matching_token = null;
314
+ let user_id: string | null = null;
315
+
316
+ for (const stored_token of all_tokens) {
317
+ try {
318
+ const token_hash = (stored_token as { token_hash: string }).token_hash;
319
+ const is_valid = await argon2.verify(token_hash, token);
320
+
321
+ if (is_valid) {
322
+ matching_token = stored_token;
323
+ user_id = (stored_token as { user_id: string }).user_id;
324
+ break;
325
+ }
326
+ } catch {
327
+ // Continue to next token if verification fails
328
+ continue;
329
+ }
330
+ }
331
+
332
+ if (!matching_token || !user_id) {
333
+ return {
334
+ success: false,
335
+ error: "Invalid or expired reset token",
336
+ };
337
+ }
338
+
339
+ // Check if token has expired
340
+ const expires_at = new Date((matching_token as { expires_at: string }).expires_at);
341
+ const now = new Date();
342
+
343
+ if (expires_at < now) {
344
+ // Delete expired token
345
+ await tokens_service.deleteById((matching_token as { id: unknown }).id);
346
+
347
+ return {
348
+ success: false,
349
+ error: "Reset token has expired",
350
+ };
351
+ }
352
+
353
+ // Get user email before updating
354
+ const users_service = createCrudService(adapter, "hazo_users");
355
+ const users = await users_service.findBy({
356
+ id: user_id,
357
+ });
358
+
359
+ if (!Array.isArray(users) || users.length === 0) {
360
+ return {
361
+ success: false,
362
+ error: "User not found",
363
+ };
364
+ }
365
+
366
+ const user = users[0];
367
+ const email = user.email_address as string;
368
+
369
+ // Hash the new password
370
+ const password_hash = await argon2.hash(new_password);
371
+
372
+ // Update user's password
373
+ const now_iso = new Date().toISOString();
374
+ await users_service.updateById(
375
+ user_id,
376
+ {
377
+ password_hash: password_hash,
378
+ changed_at: now_iso,
379
+ },
380
+ );
381
+
382
+ // Delete the used token
383
+ await tokens_service.deleteById((matching_token as { id: unknown }).id);
384
+
385
+ // Send password changed notification email
386
+ const email_result = await send_template_email("password_changed", email, {
387
+ user_email: email,
388
+ user_name: user.name as string | undefined,
389
+ });
390
+
391
+ if (!email_result.success) {
392
+ const logger = create_app_logger();
393
+ logger.error("password_reset_service_password_changed_email_failed", {
394
+ filename: "password_reset_service.ts",
395
+ line_number: 0,
396
+ user_id,
397
+ email,
398
+ error: email_result.error,
399
+ note: "Password was reset successfully but notification email failed to send",
400
+ });
401
+ }
402
+
403
+ return {
404
+ success: true,
405
+ user_id,
406
+ email,
407
+ };
408
+ } catch (error) {
409
+ const error_message =
410
+ error instanceof Error ? error.message : "Unknown error";
411
+
412
+ return {
413
+ success: false,
414
+ error: error_message,
415
+ };
416
+ }
417
+ }
418
+
@@ -0,0 +1,120 @@
1
+ // file_description: service for removing profile pictures (deleting files and clearing database)
2
+ // section: imports
3
+ import type { HazoConnectAdapter } from "hazo_connect";
4
+ import { createCrudService } from "hazo_connect/server";
5
+ import { map_db_source_to_ui } from "./profile_picture_source_mapper.js";
6
+ import { get_profile_picture_config } from "../profile_picture_config.server.js";
7
+ import { create_app_logger } from "../app_logger.js";
8
+ import fs from "fs";
9
+ import path from "path";
10
+
11
+ // section: types
12
+ export type RemoveProfilePictureResult = {
13
+ success: boolean;
14
+ error?: string;
15
+ };
16
+
17
+ // section: helpers
18
+ /**
19
+ * Removes user profile picture
20
+ * - If source is "upload": deletes the uploaded file and clears profile_picture_url and profile_source
21
+ * - If source is "gravatar" or "library": clears profile_picture_url and profile_source
22
+ * @param adapter - The hazo_connect adapter instance
23
+ * @param user_id - User ID
24
+ * @returns Remove result with success status or error
25
+ */
26
+ export async function remove_user_profile_picture(
27
+ adapter: HazoConnectAdapter,
28
+ user_id: string,
29
+ ): Promise<RemoveProfilePictureResult> {
30
+ try {
31
+ const users_service = createCrudService(adapter, "hazo_users");
32
+
33
+ // Get current user data
34
+ const users = await users_service.findBy({
35
+ id: user_id,
36
+ });
37
+
38
+ if (!Array.isArray(users) || users.length === 0) {
39
+ return {
40
+ success: false,
41
+ error: "User not found",
42
+ };
43
+ }
44
+
45
+ const current_user = users[0];
46
+ const profile_picture_url = (current_user.profile_picture_url as string) || null;
47
+ const profile_source_db = (current_user.profile_source as string) || null;
48
+
49
+ if (!profile_picture_url || !profile_source_db) {
50
+ // No profile picture to remove
51
+ return {
52
+ success: true,
53
+ };
54
+ }
55
+
56
+ // Map database source to UI source
57
+ const profile_source_ui = map_db_source_to_ui(profile_source_db);
58
+
59
+ // If source is "upload", delete the file
60
+ if (profile_source_ui === "upload") {
61
+ try {
62
+ const config = get_profile_picture_config();
63
+
64
+ if (config.upload_photo_path) {
65
+ // Extract filename from URL (e.g., /api/hazo_auth/profile_picture/user_id.jpg)
66
+ const fileName = profile_picture_url.split("/").pop();
67
+
68
+ if (fileName && fileName.startsWith(user_id)) {
69
+ // Resolve upload path
70
+ const uploadPath = path.isAbsolute(config.upload_photo_path)
71
+ ? config.upload_photo_path
72
+ : path.resolve(process.cwd(), config.upload_photo_path);
73
+
74
+ const filePath = path.join(uploadPath, fileName);
75
+
76
+ // Delete file if it exists
77
+ if (fs.existsSync(filePath)) {
78
+ fs.unlinkSync(filePath);
79
+ }
80
+ }
81
+ }
82
+ } catch (error) {
83
+ // Log error but continue with database update
84
+ const logger = create_app_logger();
85
+ const error_message = error instanceof Error ? error.message : "Unknown error";
86
+ logger.warn("profile_picture_remove_file_delete_failed", {
87
+ filename: "profile_picture_remove_service.ts",
88
+ line_number: 0,
89
+ user_id,
90
+ profile_picture_url,
91
+ error: error_message,
92
+ });
93
+ // Don't fail the request if file deletion fails - still clear the database
94
+ }
95
+ }
96
+
97
+ // Clear profile picture URL and source in database
98
+ // Note: profile_source has a CHECK constraint, so we'll set it to null
99
+ // If the database doesn't allow null, we may need to handle it differently
100
+ const update_data: Record<string, unknown> = {
101
+ changed_at: new Date().toISOString(),
102
+ profile_picture_url: null,
103
+ profile_source: null,
104
+ };
105
+
106
+ await users_service.updateById(user_id, update_data);
107
+
108
+ return {
109
+ success: true,
110
+ };
111
+ } catch (error) {
112
+ const error_message = error instanceof Error ? error.message : "Unknown error";
113
+
114
+ return {
115
+ success: false,
116
+ error: error_message,
117
+ };
118
+ }
119
+ }
120
+