Skip to content

Commit 80f2cac

Browse files
committed
feat: add email verification middleware
1 parent 85ae013 commit 80f2cac

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/Auth.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,14 @@ public function __construct()
7979
403
8080
);
8181
});
82+
83+
$this->middleware('auth.verified', function () {
84+
response()->redirect('/auth/verify');
85+
});
86+
87+
$this->middleware('auth.unverified', function () {
88+
response()->redirect('/dashboard');
89+
});
8290
}
8391

8492
/**
@@ -689,6 +697,24 @@ public function middleware(string $middleware, callable $callback)
689697
});
690698
}
691699

700+
if ($middleware === 'auth.verified') {
701+
return app()->registerMiddleware('auth.verified', function () use ($callback) {
702+
if (!$this->user() || !$this->user()->isVerified()) {
703+
$callback();
704+
exit;
705+
}
706+
});
707+
}
708+
709+
if ($middleware === 'auth.unverified') {
710+
return app()->registerMiddleware('auth.unverified', function () use ($callback) {
711+
if (!$this->user() || $this->user()->isVerified()) {
712+
$callback();
713+
exit;
714+
}
715+
});
716+
}
717+
692718
app()->registerMiddleware($middleware, $callback);
693719
}
694720

@@ -714,6 +740,37 @@ public function parseToken()
714740
}
715741
}
716742

743+
/**
744+
* Verify a user's token
745+
* @param string $token The token to verify
746+
*/
747+
public function verifyToken(string $token)
748+
{
749+
try {
750+
$decodedToken = (array) JWT::decode(
751+
$token,
752+
new Key(Config::get('token.secret') . '-verification', 'HS256')
753+
);
754+
755+
if (!isset($decodedToken['user.id'])) {
756+
$this->errorsArray['token'] = 'Invalid token';
757+
return null;
758+
}
759+
760+
$user = $this->find($decodedToken['user.id']);
761+
762+
if (!$user) {
763+
$this->errorsArray['token'] = 'User not found';
764+
return null;
765+
}
766+
767+
return true;
768+
} catch (\Throwable $th) {
769+
$this->errorsArray['token'] = $th->getMessage();
770+
return null;
771+
}
772+
}
773+
717774
/**
718775
* Return the current db instance
719776
*

0 commit comments

Comments
 (0)