File size: 11,260 Bytes
55ffa7e
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13c80ac
 
 
 
47c55a9
97b638a
 
47c55a9
97b638a
13c80ac
97b638a
 
 
 
47c55a9
97b638a
 
 
 
 
 
 
 
 
 
 
825c78a
55ffa7e
97b638a
 
 
825c78a
97b638a
825c78a
 
97b638a
55ffa7e
 
 
 
 
 
 
 
97b638a
 
55ffa7e
 
97b638a
 
 
 
 
 
13c80ac
97b638a
 
 
 
 
13c80ac
97b638a
 
 
 
 
 
 
47c55a9
55ffa7e
97b638a
 
 
 
 
 
 
 
 
 
55ffa7e
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
 
 
 
 
 
 
97b638a
 
 
55ffa7e
97b638a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
 
 
97b638a
 
 
 
 
55ffa7e
 
 
 
 
 
 
 
 
 
 
 
97b638a
 
 
 
 
 
 
55ffa7e
 
 
 
 
 
97b638a
 
 
 
 
 
 
 
55ffa7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97b638a
 
 
55ffa7e
 
 
 
97b638a
 
 
 
 
 
 
47c55a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
const { supabase, supabaseServiceRole: supabaseAdmin, createAuthClient } = require('../config/supabase');
const { success, created, error, unauthorized, serverError } = require('../utils/response');
const env = require('../config/env');

/**
 * POST /api/auth/register
 * Register a new user via Supabase Auth + create profile row.
 */
async function register(req, res) {
  try {
    const { email, password, username, display_name, role, phone } = req.body;

    // Check if username is taken
    const { data: existing } = await supabaseAdmin
      .from('profiles')
      .select('id')
      .eq('username', username)
      .single();

    if (existing) {
      return error(res, 'Username is already taken', 409, 'CONFLICT');
    }

    // Create auth user in Supabase
    const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
      email,
      password,
      email_confirm: true, // Auto-confirm for now; enable email verification later
    });

    if (authError) {
      if (authError.message.includes('already been registered')) {
        return error(res, 'Email is already registered', 409, 'CONFLICT');
      }
      return error(res, authError.message, 400);
    }

    const userId = authData.user.id;

    // NGO and Admin roles must NOT be self-assigned at registration.
    // They default to 'adopter' and require admin approval.
    const finalRole = 'adopter';

    // Create profile row (use upsert to handle cases where a trigger might have already created a skeleton profile)
    const { error: profileError } = await supabaseAdmin
      .from('profiles')
      .upsert({
        id: userId,
        role: finalRole,
        username,
        display_name: display_name || username,
        email,
        phone: phone || null,
        updated_at: new Date(),
      });

    if (profileError) {
      // Rollback: delete the auth user if profile creation fails
      await supabaseAdmin.auth.admin.deleteUser(userId);
      console.error('Profile creation failed:', profileError);
      return serverError(res, 'Failed to create user profile');
    }

    // If NGO, create a pending ngo_profiles entry
    if (role === 'ngo') {
      const { darpan_id, onboarding_answers, org_name } = req.body;
      const { error: ngoError } = await supabaseAdmin
        .from('ngo_profiles')
        .insert({
          id: userId,
          org_name: org_name || display_name || username,
          status: 'pending',
          darpan_id: darpan_id || null,
          onboarding_answers: onboarding_answers || null,
        });

      if (ngoError) {
        // Without this row the NGO application does not exist; do not leave a
        // half-registered account behind.
        console.error('NGO profile creation failed:', ngoError);
        await supabaseAdmin.auth.admin.deleteUser(userId);
        return serverError(res, 'Failed to create NGO application');
      }
    }

    // Sign in to get session tokens (on a throwaway client, never the shared one)
    const { data: session, error: signInError } = await createAuthClient().auth.signInWithPassword({
      email,
      password,
    });

    if (signInError) {
      return created(res, {
        user: { id: userId, email, role: finalRole, username },
        message: 'Account created. Please log in.',
      });
    }

    return created(res, {
      user: { id: userId, email, role: finalRole, username },
      session: {
        access_token: session.session.access_token,
        refresh_token: session.session.refresh_token,
        expires_at: session.session.expires_at,
      },
    });
  } catch (err) {
    console.error('CRITICAL Registration failure:', err);
    return serverError(res, 'Registration failed. Please try again.');
  }
}

/**
 * POST /api/auth/login
 */
async function login(req, res) {
  try {
    const { email, password } = req.body;

    const { data, error: signInError } = await createAuthClient().auth.signInWithPassword({
      email,
      password,
    });

    if (signInError) {
      return unauthorized(res, 'Invalid email or password');
    }

    // Fetch profile
    const { data: profile } = await supabaseAdmin
      .from('profiles')
      .select('id, role, username, display_name, is_banned')
      .eq('id', data.user.id)
      .single();

    if (!profile) {
      return unauthorized(res, 'User profile not found');
    }

    if (profile.is_banned) {
      return unauthorized(res, 'Your account has been suspended. Contact support.');
    }

    // If NGO, check approval status
    let ngoStatus = null;
    if (profile.role === 'ngo') {
      const { data: ngoProfile } = await supabaseAdmin
        .from('ngo_profiles')
        .select('status')
        .eq('id', profile.id)
        .single();
      ngoStatus = ngoProfile?.status || 'pending';
    }

    return success(res, {
      user: {
        id: profile.id,
        email: data.user.email,
        role: profile.role,
        username: profile.username,
        display_name: profile.display_name,
        ngo_status: ngoStatus,
      },
      session: {
        access_token: data.session.access_token,
        refresh_token: data.session.refresh_token,
        expires_at: data.session.expires_at,
      },
    });
  } catch (err) {
    console.error('Login error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/auth/me — get current user profile
 */
async function getMe(req, res) {
  try {
    const { data: profile, error: profileError } = await supabaseAdmin
      .from('profiles')
      .select('*')
      .eq('id', req.user.id)
      .single();

    if (profileError || !profile) {
      return error(res, 'Profile not found', 404);
    }

    // Looked up for every role: an NGO applicant keeps the 'adopter' role until
    // an admin approves, and still needs to see the state of their application.
    const { data: ngoProfile } = await supabaseAdmin
      .from('ngo_profiles')
      .select('*')
      .eq('id', profile.id)
      .maybeSingle();

    return success(res, {
      ...profile,
      ngo_profile: ngoProfile || null,
    });
  } catch (err) {
    console.error('GetMe error:', err);
    return serverError(res);
  }
}

/**
 * PUT /api/auth/me — update current user profile
 */
async function updateMe(req, res) {
  try {
    const { display_name, bio, phone, address } = req.body;

    const updates = {};
    if (display_name !== undefined) updates.display_name = display_name;
    if (bio !== undefined) updates.bio = bio;
    if (phone !== undefined) updates.phone = phone;
    if (address !== undefined) updates.address = address;
    updates.updated_at = new Date().toISOString();

    const { data, error: updateError } = await supabaseAdmin
      .from('profiles')
      .update(updates)
      .eq('id', req.user.id)
      .select()
      .single();

    if (updateError) {
      return error(res, updateError.message, 400);
    }

    return success(res, data);
  } catch (err) {
    console.error('UpdateMe error:', err);
    return serverError(res);
  }
}

/**
 * POST /api/auth/forgot-password
 */
async function forgotPassword(req, res) {
  try {
    const { email } = req.body;
    const redirectTo = `${env.frontendUrl}/reset-password`;

    const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, {
      redirectTo,
    });

    if (resetError) {
      console.error('Forgot password error:', resetError);
    }

    // Always return success to prevent email enumeration
    return success(res, {
      message: 'If an account with that email exists, a password reset link has been sent.',
    });
  } catch (err) {
    console.error('ForgotPassword error:', err);
    return serverError(res);
  }
}

/**
 * POST /api/auth/reset-password
 * The reset email links to the frontend with a recovery access token in the
 * URL hash. The frontend sends that token as the Bearer credential; the
 * password is changed for the user that token belongs to, and nobody else.
 */
async function resetPassword(req, res) {
  try {
    const { new_password } = req.body;

    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return unauthorized(res, 'Reset link is missing or has expired. Request a new one.');
    }
    const token = authHeader.split(' ')[1];

    const { data: userData, error: userError } = await supabase.auth.getUser(token);
    if (userError || !userData?.user) {
      return unauthorized(res, 'Reset link is invalid or has expired. Request a new one.');
    }

    const { error: updateError } = await supabaseAdmin.auth.admin.updateUserById(userData.user.id, {
      password: new_password,
    });

    if (updateError) {
      return error(res, updateError.message, 400);
    }

    // End every session of this user, including the recovery one.
    const { error: signOutError } = await supabaseAdmin.auth.admin.signOut(token, 'global');
    if (signOutError) {
      console.error('ResetPassword sign-out error:', signOutError);
    }

    return success(res, { message: 'Password has been reset successfully.' });
  } catch (err) {
    console.error('ResetPassword error:', err);
    return serverError(res);
  }
}

/**
 * POST /api/auth/refresh — exchange a refresh token for a new session
 */
async function refresh(req, res) {
  try {
    const { refresh_token } = req.body;

    const { data, error: refreshError } = await createAuthClient().auth.refreshSession({ refresh_token });

    if (refreshError || !data?.session) {
      return unauthorized(res, 'Session expired. Please log in again.');
    }

    return success(res, {
      session: {
        access_token: data.session.access_token,
        refresh_token: data.session.refresh_token,
        expires_at: data.session.expires_at,
      },
    });
  } catch (err) {
    console.error('Refresh error:', err);
    return serverError(res);
  }
}

/**
 * POST /api/auth/logout — revoke the caller's own session only
 */
async function logout(req, res) {
  try {
    const { error: signOutError } = await supabaseAdmin.auth.admin.signOut(req.supabaseToken, 'local');
    if (signOutError) {
      console.error('Logout error:', signOutError);
    }
    return success(res, { message: 'Logged out successfully.' });
  } catch (err) {
    console.error('Logout error:', err);
    return serverError(res);
  }
}

/**
 * GET /api/auth/authorize/:provider
 * Get the Supabase OAuth URL to redirect the frontend
 */
async function authorizeSocial(req, res) {
  try {
    const { provider } = req.params;
    const validProviders = ['google', 'apple', 'facebook'];
    
    if (!validProviders.includes(provider)) {
      return error(res, 'Invalid provider', 400);
    }

    const { data, error: oauthError } = await supabase.auth.signInWithOAuth({
      provider,
      options: {
        redirectTo: `${env.frontendUrl}/auth/callback`,
      },
    });

    if (oauthError) {
      return error(res, oauthError.message, 400);
    }

    return success(res, { url: data.url });
  } catch (err) {
    console.error('authorizeSocial error:', err);
    return serverError(res);
  }
}

module.exports = { register, login, getMe, updateMe, forgotPassword, resetPassword, refresh, logout, authorizeSocial };