feat(mobile): implement real email verification screen and flows

This commit is contained in:
micko samawa 2026-06-28 14:54:49 +07:00
parent ff3f43703e
commit 1d681b483e
11 changed files with 669 additions and 9 deletions

View File

@ -32,6 +32,9 @@ public function register(RegisterRequest $request)
// Refresh user to ensure all fields are loaded from DB
$user->refresh();
// Fire registered event to trigger verification email notification
event(new \Illuminate\Auth\Events\Registered($user));
$token = $user->createToken('mobile-app-token')->plainTextToken;
Log::info('Registration successful', ['user_id' => $user->id]);

View File

@ -2,13 +2,13 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
class User extends Authenticatable implements MustVerifyEmail
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable, HasApiTokens;

View File

@ -0,0 +1,205 @@
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Berhasil Diverifikasi</title>
<!-- Google Fonts: Outfit -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700;800&display=swap" rel="stylesheet">
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Outfit', sans-serif;
background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
color: #f1f5f9;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
overflow-x: hidden;
}
.container {
width: 100%;
max-width: 480px;
text-align: center;
}
/* Glassmorphism Card */
.card {
background: rgba(30, 41, 59, 0.7);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 24px;
padding: 40px 30px;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
animation: slideUp 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
/* Checkmark Animation */
.icon-wrapper {
width: 80px;
height: 80px;
border-radius: 50%;
background: linear-gradient(135deg, #22c55e 0%, #15803d 100%);
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 24px;
box-shadow: 0 10px 25px rgba(34, 197, 94, 0.3);
animation: popIn 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 0.3s both;
}
.icon-wrapper svg {
width: 40px;
height: 40px;
color: white;
stroke-dasharray: 100;
stroke-dashoffset: 100;
animation: drawCheck 0.8s ease-in-out 0.8s both;
}
h1 {
font-size: 24px;
font-weight: 800;
color: #ffffff;
margin-bottom: 12px;
letter-spacing: -0.5px;
line-height: 1.2;
}
p {
font-size: 15px;
color: #94a3b8;
line-height: 1.6;
margin-bottom: 24px;
font-weight: 400;
}
.user-badge {
background: rgba(255, 255, 255, 0.04);
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 12px;
padding: 12px 16px;
margin-bottom: 30px;
display: inline-block;
max-width: 100%;
}
.user-name {
font-size: 14px;
font-weight: 700;
color: #38bdf8;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.user-email {
font-size: 12px;
color: #64748b;
margin-top: 2px;
}
.footer-note {
font-size: 12px;
color: #64748b;
margin-top: 10px;
}
.glow-button {
display: block;
width: 100%;
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white;
text-decoration: none;
padding: 14px 24px;
font-size: 15px;
font-weight: 600;
border-radius: 12px;
box-shadow: 0 4px 15px rgba(59, 130, 246, 0.4);
transition: all 0.3s ease;
cursor: pointer;
border: none;
}
.glow-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(59, 130, 246, 0.6);
background: linear-gradient(135deg, #60a5fa 0%, #2563eb 100%);
}
.glow-button:active {
transform: translateY(0);
}
/* Animations */
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes popIn {
from {
opacity: 0;
transform: scale(0.6);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes drawCheck {
to {
stroke-dashoffset: 0;
}
}
</style>
</head>
<body>
<div class="container">
<div class="card">
<div class="icon-wrapper">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
</div>
<h1>Email Terverifikasi!</h1>
<p>Terima kasih. Email Anda telah berhasil diverifikasi secara aman. Akun Anda kini telah aktif sepenuhnya.</p>
<div class="user-badge">
<div class="user-name">{{ $name }}</div>
<div class="user-email">{{ $email }}</div>
</div>
<button class="glow-button" onclick="closeWindow()">Kembali ke Aplikasi</button>
<div class="footer-note">Anda dapat menutup halaman browser ini sekarang.</div>
</div>
</div>
<script>
function closeWindow() {
// Coba menutup tab secara otomatis (hanya bekerja di browser mobile tertentu)
window.close();
// Alternatif jika close() di-block browser
alert("Email Anda sudah terverifikasi. Silakan buka kembali aplikasi mobile Kontrak Kampus Anda!");
}
</script>
</body>
</html>

View File

@ -167,6 +167,23 @@
});
Route::post('/logout', [AuthController::class, 'logout']);
Route::put('/profile/update', [AuthController::class, 'updateProfile']);
// Send/Resend Email Verification Notification
Route::post('/email/verification-notification', function (Request $request) {
if ($request->user()->hasVerifiedEmail()) {
return response()->json([
'success' => false,
'message' => 'Email Anda sudah diverifikasi.',
], 400);
}
$request->user()->sendEmailVerificationNotification();
return response()->json([
'success' => true,
'message' => 'Tautan verifikasi baru telah dikirim ke email Anda.',
]);
})->middleware('throttle:3,1');
// Booking Routes
Route::prefix('bookings')->group(function () {

View File

@ -212,3 +212,29 @@
Route::post('/admin/logout', [AdminAuthController::class, 'logout'])->name('admin.logout');
});
// -------------------------------------------------
// EMAIL VERIFICATION LANDING PAGE (PUBLIC - SIGNED)
// -------------------------------------------------
Route::get('/email/verify/{id}/{hash}', function ($id, $hash, \Illuminate\Http\Request $request) {
// Temukan user berdasarkan ID
$user = \App\Models\User::findOrFail($id);
// Verifikasi hash email
if (! hash_equals((string) $hash, sha1($user->getEmailForVerification()))) {
abort(403, 'Tautan verifikasi tidak valid.');
}
// Tandai email sebagai terverifikasi
if (! $user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
event(new \Illuminate\Auth\Events\Verified($user));
}
// Kembalikan view sukses yang indah
return view('auth.verified_success', [
'name' => $user->name,
'email' => $user->email
]);
})->middleware(['signed', 'throttle:6,1'])->name('verification.verify');

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'screens/improved_home_screen.dart';
import 'screens/email_verification_screen.dart';
import 'register.dart';
import 'services/auth_service.dart';
@ -234,10 +235,15 @@ class _LoginScreenState extends State<LoginScreen> {
final success = result['success'] ?? false;
if (success == true) {
final user = _authService.currentUser;
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const ImprovedHomeScreen()),
MaterialPageRoute(
builder: (context) => user?.isEmailVerified == true
? const ImprovedHomeScreen()
: const EmailVerificationScreen(),
),
);
}
} else {

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'login.dart';
import 'screens/improved_home_screen.dart';
import 'screens/email_verification_screen.dart';
import 'services/auth_service.dart';
import 'services/server_discovery_service.dart';
@ -311,7 +312,9 @@ class _SplashScreenState extends State<SplashScreen>
if (!mounted) return;
final destination = _authService.isAuthenticated
? const ImprovedHomeScreen()
? (_authService.currentUser?.isEmailVerified == true
? const ImprovedHomeScreen()
: const EmailVerificationScreen())
: const LoginScreen();
Navigator.pushReplacement(

View File

@ -7,6 +7,7 @@ class User {
final String? roleLabel;
final String? userType;
final DateTime? createdAt;
final DateTime? emailVerifiedAt;
User({
required this.id,
@ -17,6 +18,7 @@ class User {
this.roleLabel,
this.userType,
this.createdAt,
this.emailVerifiedAt,
});
factory User.fromJson(Map<String, dynamic> json) {
@ -31,6 +33,9 @@ class User {
createdAt: json['created_at'] != null
? DateTime.parse(json['created_at'])
: null,
emailVerifiedAt: json['email_verified_at'] != null
? DateTime.parse(json['email_verified_at'])
: null,
);
}
@ -61,6 +66,9 @@ class User {
/// Check if user is super admin
bool isSuperAdmin() => role == 'super_admin';
/// Check if email is verified
bool get isEmailVerified => emailVerifiedAt != null;
Map<String, dynamic> toJson() {
return {
'id': id,
@ -71,6 +79,7 @@ class User {
'role_label': roleLabel,
'user_type': userType,
'created_at': createdAt?.toIso8601String(),
'email_verified_at': emailVerifiedAt?.toIso8601String(),
};
}
}

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'login.dart';
import 'screens/email_verification_screen.dart';
import 'services/auth_service.dart';
class RegisterScreen extends StatefulWidget {
@ -493,7 +494,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
size: 20,
),
SizedBox(width: 10),
Text('Registrasi berhasil! Silakan login.'),
Text('Registrasi berhasil! Silakan verifikasi email Anda.'),
],
),
backgroundColor: const Color(0xFF2E7D32),
@ -512,7 +513,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => LoginScreen(initialEmail: _emailController.text),
builder: (_) => const EmailVerificationScreen(),
),
);
}

View File

@ -0,0 +1,355 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../services/auth_service.dart';
import 'improved_home_screen.dart';
import '../login.dart';
class EmailVerificationScreen extends StatefulWidget {
const EmailVerificationScreen({super.key});
@override
State<EmailVerificationScreen> createState() => _EmailVerificationScreenState();
}
class _EmailVerificationScreenState extends State<EmailVerificationScreen> {
final _authService = AuthService();
bool _isLoading = false;
bool _isResending = false;
int _cooldownSeconds = 0;
Timer? _cooldownTimer;
String? _message;
bool _isSuccessMessage = true;
@override
void initState() {
super.initState();
// Auto-check once on load
_checkVerificationStatus(silent: true);
}
@override
void dispose() {
_cooldownTimer?.cancel();
super.dispose();
}
void _startCooldown() {
setState(() => _cooldownSeconds = 60);
_cooldownTimer?.cancel();
_cooldownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (_cooldownSeconds > 0) {
setState(() => _cooldownSeconds--);
} else {
_cooldownTimer?.cancel();
}
});
}
Future<void> _checkVerificationStatus({bool silent = false}) async {
if (!mounted) return;
if (!silent) {
setState(() {
_isLoading = true;
_message = null;
});
}
// Refresh user data from API
final user = await _authService.getCurrentUser();
if (!mounted) return;
setState(() => _isLoading = false);
if (user != null && user.isEmailVerified) {
// Success! Go to Home Screen
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Row(
children: [
const Icon(Icons.check_circle, color: Colors.white),
const SizedBox(width: 8),
Text('Selamat, email Anda telah terverifikasi!'),
],
),
backgroundColor: Colors.green[700],
),
);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const ImprovedHomeScreen()),
);
}
} else {
if (!silent) {
setState(() {
_message = 'Email belum diverifikasi. Silakan klik tautan di inbox Anda lalu coba lagi.';
_isSuccessMessage = false;
});
}
}
}
Future<void> _handleResendEmail() async {
if (_cooldownSeconds > 0) return;
setState(() {
_isResending = true;
_message = null;
});
final result = await _authService.resendVerificationEmail();
if (!mounted) return;
setState(() => _isResending = false);
if (result['success'] == true) {
_startCooldown();
setState(() {
_message = 'Link verifikasi baru telah dikirim ke email Anda.';
_isSuccessMessage = true;
});
} else {
setState(() {
_message = result['message'] ?? 'Gagal mengirim email verifikasi.';
_isSuccessMessage = false;
});
}
}
Future<void> _handleLogout() async {
setState(() => _isLoading = true);
await _authService.logout();
if (!mounted) return;
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const LoginScreen()),
);
}
@override
Widget build(BuildContext context) {
final user = _authService.currentUser;
final email = user?.email ?? '';
return Scaffold(
backgroundColor: const Color(0xFFF3F7FB),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Icon Animation / Header
Container(
padding: const EdgeInsets.all(28),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: const SpinKitDoubleBounce(
color: Color(0xFF1565C0),
size: 60,
),
),
const SizedBox(height: 32),
// Card Container
Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.03),
blurRadius: 15,
offset: const Offset(0, 5),
),
],
),
child: Column(
children: [
const Text(
'Verifikasi Email Anda',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w800,
color: Color(0xFF1A1A2E),
letterSpacing: -0.5,
),
),
const SizedBox(height: 12),
RichText(
textAlign: TextAlign.center,
text: TextSpan(
style: const TextStyle(
fontSize: 14,
color: Color(0xFF5A6B85),
height: 1.5,
),
children: [
const TextSpan(text: 'Kami telah mengirimkan link verifikasi ke email: \n'),
TextSpan(
text: email,
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Color(0xFF1565C0),
),
),
const TextSpan(
text: '\n\nSilakan buka kotak masuk (atau folder spam) Anda, klik link tersebut, kemudian kembali ke aplikasi ini.',
),
],
),
),
const SizedBox(height: 24),
// Status Message Box if any
if (_message != null) ...[
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _isSuccessMessage ? Colors.green[50] : Colors.orange[50],
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: _isSuccessMessage
? Colors.green[200]!
: Colors.orange[200]!,
),
),
child: Row(
children: [
Icon(
_isSuccessMessage
? Icons.check_circle_outline
: Icons.info_outline,
color: _isSuccessMessage ? Colors.green[700] : Colors.orange[700],
size: 20,
),
const SizedBox(width: 10),
Expanded(
child: Text(
_message!,
style: TextStyle(
fontSize: 12,
color: _isSuccessMessage
? Colors.green[800]
: Colors.orange[800],
fontWeight: FontWeight.w500,
height: 1.4,
),
),
),
],
),
),
const SizedBox(height: 24),
],
// Button Saya Sudah Verifikasi
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isLoading ? null : () => _checkVerificationStatus(),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF1565C0),
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
),
child: _isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2.5,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.verified, size: 18, color: Colors.white),
SizedBox(width: 8),
Text(
'SAYA SUDAH VERIFIKASI',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
),
),
const SizedBox(height: 12),
// Button Resend Email
SizedBox(
width: double.infinity,
child: OutlinedButton(
onPressed: (_isResending || _cooldownSeconds > 0)
? null
: _handleResendEmail,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
side: const BorderSide(color: Color(0xFFE2EAF3)),
),
child: _isResending
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(
_cooldownSeconds > 0
? 'KIRIM ULANG EMAIL ($_cooldownSeconds s)'
: 'KIRIM ULANG EMAIL VERIFIKASI',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: _cooldownSeconds > 0 ? Colors.grey : const Color(0xFF1565C0),
),
),
),
),
],
),
),
const SizedBox(height: 24),
// Button Logout/Back to Login
TextButton(
onPressed: _isLoading ? null : _handleLogout,
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.logout, size: 16),
SizedBox(width: 6),
Text('Keluar / Ganti Akun'),
],
),
),
],
),
),
),
),
);
}
}

View File

@ -1,4 +1,4 @@
import 'dart:async';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
@ -547,8 +547,10 @@ class AuthService {
if (user.name.trim().isNotEmpty || user.email.trim().isNotEmpty) {
_currentUser = user;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(AppConfig.userKey, jsonEncode(user.toJson()));
await _secureStorage.write(
key: AppConfig.userKey,
value: jsonEncode(user.toJson()),
);
return user;
}
@ -562,6 +564,39 @@ class AuthService {
}
}
/// Mengirim ulang email verifikasi
Future<Map<String, dynamic>> resendVerificationEmail() async {
if (_token == null) {
return {'success': false, 'message': 'Sesi telah habis. Silakan login kembali.'};
}
try {
final response = await http.post(
Uri.parse('${AppConfig.baseUrl}/email/verification-notification'),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $_token',
},
).timeout(AppConfig.connectionTimeout);
final decoded = jsonDecode(response.body);
if (response.statusCode == 200) {
return {
'success': true,
'message': decoded['message'] ?? 'Tautan verifikasi terkirim!'
};
} else {
return {
'success': false,
'message': decoded['message'] ?? 'Gagal mengirim email verifikasi.'
};
}
} catch (e) {
return {'success': false, 'message': 'Koneksi bermasalah: $e'};
}
}
// Update profile
Future<Map<String, dynamic>> updateProfile({
required String name,