Repository navigation
Expand file tree
/
Copy pathAuthController.php
More file actions
307 lines (253 loc) · 11 KB
/
Copy pathAuthController.php
File metadata and controls
307 lines (253 loc) · 11 KB
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
<?php
namespace App\Http\Controllers;
use App\Models\AppSetting;
use App\Models\User;
use App\Models\UserAppreciation;
use App\Notifications\UserAppreciationNotification;
use App\Notifications\WelcomeNotification;
use App\Rules\CleanText;
use App\Services\ChatProfanityFilter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Laravel\Socialite\Facades\Socialite;
class AuthController extends Controller
{
//
public function index()
{
if (Auth::check()) {
return redirect()->route('me');
}
$allowRegistration = (bool) AppSetting::get('allow_registration', true);
return Inertia::render('auth/Login', [
'allowRegistration' => $allowRegistration,
]);
}
public function redirectToGoogle(Request $request)
{
if (Auth::check()) {
return redirect()->route('me');
}
if ($request->filled('redirect')) {
$redirectUrl = $request->query('redirect');
if (str_starts_with($redirectUrl, '/') && ! str_starts_with($redirectUrl, '//')) {
session(['url.intended' => url($redirectUrl)]);
} else {
$host = parse_url($redirectUrl, PHP_URL_HOST);
$appHost = parse_url(config('app.url'), PHP_URL_HOST);
if ($host && $appHost && ($host === $appHost || str_ends_with($host, '.'.$appHost) || $host === 'localhost')) {
session(['url.intended' => $redirectUrl]);
}
}
}
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback(Request $request)
{
try {
$googleUser = Socialite::driver('google')->user();
} catch (\Throwable $e) {
report($e);
return redirect()->route('login')->with('error', 'Failed to authenticate. Refresh the page & try again.');
}
$user = User::where('google_id', $googleUser->getId())
->orWhere('email', $googleUser->getEmail())
->first();
if ($user) {
$user->update([
'google_id' => $googleUser->getId(),
'email_verified_at' => $user->email_verified_at ?? now(),
]);
Auth::login($user, remember: true);
$request->session()->regenerate();
$defaultUrl = $user->username
? route('user.profile', $user->username)
: route('profile.edit');
return redirect()->intended($defaultUrl);
}
$allowRegistration = (bool) AppSetting::get('allow_registration', true);
if (! $allowRegistration) {
return redirect()->route('login')->with('error', 'রেজিস্ট্রেশন সাময়িকভাবে স্থগিত রাখা হয়েছে। পূর্বে তৈরিকৃত অ্যাকাউন্ট দিয়ে লগইন করতে পারেন।');
}
$rawName = $googleUser->getName() ?? $googleUser->getNickname() ?? '';
$cleanGoogleName = ChatProfanityFilter::hasProfanity($rawName) ? 'Student' : $rawName;
$request->session()->put('onboarding_user', [
'google_id' => $googleUser->getId(),
'email' => $googleUser->getEmail(),
'name' => $cleanGoogleName,
'avatar' => $googleUser->getAvatar() ?? null,
]);
return redirect()->route('onboarding');
}
public function showOnboarding(Request $request)
{
if (Auth::check()) {
return redirect()->route('index');
}
if (! $request->session()->has('onboarding_user')) {
return redirect()->route('login')->with('error', 'Please continue with Google to create an account.');
}
$suggestedContributors = User::withCount('appreciationsReceived')
->orderByDesc('priority')
->orderByDesc('appreciations_received_count')
->latest('id')
->take(4)
->get(['id', 'name', 'username', 'image_path', 'institution', 'is_verified']);
return Inertia::render('auth/Onboarding', [
'user' => $request->session()->get('onboarding_user'),
'suggestedContributors' => $suggestedContributors,
]);
}
public function checkUsername(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => [
'required',
'string',
'min:3',
'max:30',
'regex:/^[a-zA-Z0-9_]+$/',
'unique:users,username',
new CleanText,
],
], [
'username.required' => 'Please choose a username.',
'username.min' => 'Username must be at least 3 characters.',
'username.max' => 'Username cannot exceed 30 characters.',
'username.regex' => "Username can only contain letters, numbers, and underscores. Dots aren't allowed.",
'username.unique' => 'This username is already taken. Please choose another one.',
]);
if ($validator->fails()) {
return response()->json([
'available' => false,
'message' => $validator->errors()->first('username'),
], 422);
}
return response()->json([
'available' => true,
'message' => 'Username is available.',
]);
}
public function completeOnboarding(Request $request)
{
if (Auth::check()) {
return redirect()->route('index');
}
if (! $request->session()->has('onboarding_user')) {
return redirect()->route('login')->with('error', 'Session expired. Please continue with Google again.');
}
$onboardingData = $request->session()->get('onboarding_user');
$validated = $request->validate([
'name' => ['required', 'string', 'max:255', new CleanText],
'username' => [
'required',
'string',
'min:3',
'max:30',
'regex:/^[a-zA-Z0-9_]+$/',
'unique:users,username',
new CleanText,
],
'school' => ['required', 'string', 'max:255', new CleanText],
'image' => ['sometimes', 'nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:5120'],
'receive_emails' => ['required', 'boolean'],
'appreciations' => ['nullable', 'array', 'max:4'],
'appreciations.*' => ['integer', 'distinct', 'exists:users,id'],
], [
'school.required' => 'Please enter your school, college, or institution name.',
'username.regex' => "Username can only contain letters, numbers, and underscores. Dots aren't allowed.",
'username.unique' => 'This username is already taken. Please choose another one.',
'image.image' => 'The uploaded file must be an image (PNG, JPG, JPEG, WEBP).',
'image.max' => 'The profile image may not be greater than 5MB.',
]);
$imagePath = null;
if ($request->hasFile('image')) {
$imagePath = $request->file('image')->store('users/profile-images');
} elseif (! empty($onboardingData['avatar'])) {
$imagePath = $this->downloadGoogleAvatar($onboardingData['avatar']);
}
$user = User::create([
'name' => $validated['name'],
'username' => $validated['username'],
'email' => $onboardingData['email'],
'google_id' => $onboardingData['google_id'],
'institution' => $validated['school'],
'image_path' => $imagePath,
'receive_emails' => $validated['receive_emails'],
'email_verified_at' => now(),
]);
$user->notify(new WelcomeNotification);
if (! empty($validated['appreciations'])) {
foreach ($validated['appreciations'] as $targetUserId) {
if ((int) $targetUserId !== (int) $user->id) {
$targetUser = User::find($targetUserId);
if ($targetUser) {
UserAppreciation::create([
'user_id' => $targetUser->id,
'appreciator_id' => $user->id,
]);
$totalAppreciations = $targetUser->appreciationsReceived()->count();
UserAppreciationNotification::sendTo($targetUser, $user, $totalAppreciations);
}
}
}
}
$request->session()->forget('onboarding_user');
Auth::login($user, remember: true);
$request->session()->regenerate();
$defaultUrl = $user->username
? route('user.profile', $user->username)
: route('profile.edit');
$targetUrl = $request->session()->pull('url.intended', $defaultUrl);
$targetHost = parse_url($targetUrl, PHP_URL_HOST);
$appHost = parse_url(config('app.url'), PHP_URL_HOST);
if ($targetHost && $appHost && $targetHost !== $appHost) {
return Inertia::location($targetUrl);
}
return redirect()->to($targetUrl)->with('success', 'Account created successfully! Welcome to HSCStack.');
}
private function downloadGoogleAvatar(?string $avatarUrl): ?string
{
if (! $avatarUrl) {
return null;
}
try {
// Replace small size parameter (=s96-c) with high-res (=s500-c) if present
$highResUrl = preg_replace('/=s\d+(-c)?$/i', '=s500-c', $avatarUrl);
$verifySsl = config('services.google.guzzle.verify', true);
$response = Http::withOptions(['verify' => $verifySsl])->timeout(6)->get($highResUrl);
if (! $response->successful()) {
// Fallback to original URL if high-res request fails
$response = Http::withOptions(['verify' => $verifySsl])->timeout(6)->get($avatarUrl);
}
if ($response->successful()) {
$contents = $response->body();
$extension = 'jpg';
$contentType = (string) $response->header('Content-Type');
if (str_contains($contentType, 'png')) {
$extension = 'png';
} elseif (str_contains($contentType, 'webp')) {
$extension = 'webp';
}
$filename = 'users/profile-images/'.Str::random(40).'.'.$extension;
Storage::put($filename, $contents);
return $filename;
}
} catch (\Throwable $e) {
report($e);
}
return null;
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('index');
}
}