File size: 12,500 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace App\Http\Controllers\Api;

use App\Actions\EmailConfirmation;
use App\Helpers\Classes\Helper;
use App\Http\Controllers\Controller;
use App\Jobs\SendConfirmationEmail;
use App\Jobs\SendPasswordResetEmail;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
    /**
     * @OA\Post(
     *      path="/api/auth/register",
     *      operationId="register",
     *      tags={"Authentication"},
     *      summary="Register a new user",
     *      description="Registers a new user with the provided data",
     *
     *      @OA\RequestBody(
     *          required=true,
     *
     *          @OA\JsonContent(
     *              required={"name", "surname", "email", "password", "password_confirmation"},
     *
     *              @OA\Property(property="name", type="string", example="John"),
     *              @OA\Property(property="surname", type="string", example="Doe"),
     *              @OA\Property(property="email", type="string", format="email", example="john.doe@example.com"),
     *              @OA\Property(property="password", type="string", format="password", example="password123"),
     *              @OA\Property(property="password_confirmation", type="string", format="password", example="password123"),
     *              @OA\Property(property="affiliate_code", type="string", nullable=true, example="your_affiliate_code"),
     *          ),
     *      ),
     *
     *      @OA\Response(
     *          response=201,
     *          description="User registered successfully",
     *      ),
     *      @OA\Response(
     *          response=422,
     *          description="Validation error or user already exists",
     *      ),
     * )
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'     => ['required', 'string', 'max:255'],
            'surname'  => ['required', 'string', 'max:255'],
            'email'    => ['required', 'string', 'email', 'max:255', 'unique:' . User::class],
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        $affCode = null;
        if ($request->affiliate_code != null) {
            $affUser = User::where('affiliate_code', $request->affiliate_code)->first();
            if ($affUser != null) {
                $affCode = $affUser->id;
            }
        }

        if (Helper::appIsDemo()) {
            $user = User::create([
                'name'                    => $request->name,
                'surname'                 => $request->surname,
                'email'                   => $request->email,
                'email_confirmation_code' => Str::random(67),
                'remaining_words'         => 5000,
                'remaining_images'        => 200,
                'password'                => Hash::make($request->password),
                'email_verification_code' => Str::random(67),
                'affiliate_id'            => $affCode,
                'affiliate_code'          => Str::upper(Str::random(12)),
            ]);
        } else {
            $settings = Setting::first();
            $user = User::create([
                'name'                    => $request->name,
                'surname'                 => $request->surname,
                'email'                   => $request->email,
                'email_confirmation_code' => Str::random(67),
                'remaining_words'         => explode(',', $settings->free_plan)[0],
                'remaining_images'        => explode(',', $settings->free_plan)[1] ?? 0,
                'password'                => Hash::make($request->password),
                'email_verification_code' => Str::random(67),
                'affiliate_id'            => $affCode,
                'affiliate_code'          => Str::upper(Str::random(12)),
            ]);
        }

        //event(new Registered($user));

        // the email confirmation process gonna be inside the app?
        // dispatch(new SendConfirmationEmail($user));
        // $settings = Setting::first();
        // if ($settings->login_without_confirmation == 1) {
        //     Auth::login($user);
        // } else {
        //     $data = array(
        //         'errors' => ['We have sent you an email for account confirmation. Please confirm your account to continue.'],
        //         'type' => 'confirmation',
        //     );
        //     return response()->json($data, 401);
        // }

        return response()->json('OK', 200);
    }

    /**
     * @OA\Post(
     *      path="/api/auth/logout",
     *      operationId="logout",
     *      tags={"Authentication"},
     *      summary="Logout the authenticated user",
     *      description="Logs out the authenticated user and revokes the access token",
     *      security={{ "passport": {} }},
     *
     *      @OA\Response(
     *          response=200,
     *          description="Logout successful",
     *      ),
     *      @OA\Response(
     *          response=401,
     *          description="Unauthenticated",
     *      ),
     * )
     */
    public function logout(Request $request)
    {
        $request->user()->tokens()->each(function ($token, $key) {
            $token->delete();
        });

        return response()->json(['message' => 'Logout successful'], 200);
    }

    /**
     * Send a password reset link to the given user.
     *
     * @OA\Post(
     *      path="/api/auth/forgot-password",
     *      operationId="forgotPassword",
     *      tags={"Authentication"},
     *      summary="Initiate password reset",
     *      description="Initiate the password reset process by sending an email with a reset link.",
     *
     *      @OA\RequestBody(
     *          required=true,
     *
     *          @OA\JsonContent(
     *              required={"email"},
     *
     *              @OA\Property(property="email", type="string", format="email", example="user@example.com"),
     *          ),
     *      ),
     *
     *      @OA\Response(
     *          response=200,
     *          description="Password reset link sent successfully",
     *      ),
     *      @OA\Response(
     *          response=422,
     *          description="Validation error or user not found",
     *      ),
     * )
     */
    public function sendPasswordResetMail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => ['required', 'email'],
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        $user = User::where('email', $request->email)->first();

        if ($user !== null) {
            $user->password_reset_code = Str::random(67);
            $user->save();

            // Dispatch the job to send the password reset email asynchronously
            dispatch(new SendPasswordResetEmail($user));

            return response()->json(['message' => __('Password reset link sent successfully')], 200);
        } else {
            return response()->json(['error' => __('User not found')], 422);
        }
    }

    /**
     * Verify user's email using the provided confirmation code.
     *
     * @OA\Get(
     *      path="/api/auth/email/verify",
     *      operationId="verifyEmail",
     *      tags={"Authentication"},
     *      summary="Verify user's email",
     *      description="Verify the user's email using the provided confirmation code.",
     *
     *      @OA\Parameter(
     *          name="email_confirmation_code",
     *          in="query",
     *          required=true,
     *          description="Email confirmation code",
     *
     *          @OA\Schema(type="string"),
     *      ),
     *
     *      @OA\Response(
     *          response=200,
     *          description="Email verified successfully",
     *      ),
     *      @OA\Response(
     *          response=422,
     *          description="Validation error or user not found",
     *      ),
     * )
     */
    public function emailConfirmationMail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email_confirmation_code' => ['required', 'string'],
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        $user = User::where('email_confirmation_code', $request->email_confirmation_code)->first();

        if ($user !== null) {
            $user->email_confirmation_code = null;
            $user->email_confirmed = 1;
            $user->status = 1;
            $user->save();

            return response()->json(['message' => 'Email verified successfully'], 200);
        } else {
            return response()->json(['error' => __('Email not found')], 422);
        }
    }

    /**
     * Resend the confirmation email.
     *
     * @OA\Post(
     *      path="/api/auth/email/verify/resend",
     *      operationId="resendConfirmationEmail",
     *      tags={"Authentication"},
     *      summary="Resend confirmation email",
     *      description="Resend the confirmation email to the user if not already verified.",
     *
     *      @OA\RequestBody(
     *          required=true,
     *
     *          @OA\JsonContent(
     *              required={"email"},
     *
     *              @OA\Property(property="email", type="string", format="email", example="user@example.com"),
     *          ),
     *      ),
     *
     *      @OA\Response(
     *          response=200,
     *          description="Confirmation email resent successfully",
     *
     *          @OA\JsonContent(
     *              type="object",
     *              example={"message": "Confirmation email resent successfully"},
     *          ),
     *      ),
     *
     *      @OA\Response(
     *          response=403,
     *          description="Email already verified",
     *
     *          @OA\JsonContent(
     *              type="object",
     *              example={"error": "Email already verified"},
     *          ),
     *      ),
     * )
     */
    public function resend(Request $request): JsonResponse
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        $user = User::where('email', $request->email)->firstOrFail();

        if (! $user->isConfirmed() && ! $user->isAdmin()) {
            EmailConfirmation::forUser($user)->resend();

            return response()->json(['message' => __('Confirmation email resent successfully')], 200);
        }

        return response()->json(['error' => __('Email not found or already verified')], 403);
    }

    /**
     * Get actively supported login methods.
     *
     * @OA\Get(
     *      path="/api/auth/social-login",
     *      operationId="getSupportedLoginMethods",
     *      tags={"Authentication"},
     *      summary="Get supported login methods",
     *      description="Get actively supported login methods as a list.",
     *
     *      @OA\Response(
     *          response=200,
     *          description="Successful operation",
     *
     *          @OA\JsonContent(
     *              type="array",
     *
     *              @OA\Items(
     *                  type="string",
     *                  example="github",
     *              ),
     *              example={"github", "google"},
     *          ),
     *      ),
     * )
     */
    public function getSupportedLoginMethods(): JsonResponse
    {
        $setting = Setting::first();

        $supportedLoginMethods = [];

        if ($setting->github_active) {
            $supportedLoginMethods[] = 'github';
        }

        if ($setting->twitter_active) {
            $supportedLoginMethods[] = 'twitter';
        }

        if ($setting->google_active) {
            $supportedLoginMethods[] = 'google';
        }

        if ($setting->facebook_active) {
            $supportedLoginMethods[] = 'facebook';
        }

        return response()->json($supportedLoginMethods, 200);
    }
}