├── .editorconfig ├── .env.example ├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── app ├── Auth │ └── JwtGuard.php ├── Console │ └── Kernel.php ├── Contracts │ ├── JwtBuilderInterface.php │ ├── JwtGeneratorInterface.php │ ├── JwtParserInterface.php │ ├── JwtSubjectInterface.php │ ├── JwtTokenInterface.php │ └── JwtValidatorInterface.php ├── Exceptions │ ├── Handler.php │ └── JwtParseException.php ├── Http │ ├── Controllers │ │ ├── Api │ │ │ ├── Articles │ │ │ │ ├── ArticleController.php │ │ │ │ ├── CommentsController.php │ │ │ │ └── FavoritesController.php │ │ │ ├── AuthController.php │ │ │ ├── ProfileController.php │ │ │ ├── TagsController.php │ │ │ └── UserController.php │ │ └── Controller.php │ ├── Kernel.php │ ├── Middleware │ │ ├── Authenticate.php │ │ ├── EncryptCookies.php │ │ ├── PreventRequestsDuringMaintenance.php │ │ ├── RedirectIfAuthenticated.php │ │ ├── TrimStrings.php │ │ ├── TrustHosts.php │ │ ├── TrustProxies.php │ │ └── VerifyCsrfToken.php │ ├── Requests │ │ └── Api │ │ │ ├── ArticleListRequest.php │ │ │ ├── BaseArticleRequest.php │ │ │ ├── FeedRequest.php │ │ │ ├── LoginRequest.php │ │ │ ├── NewArticleRequest.php │ │ │ ├── NewCommentRequest.php │ │ │ ├── NewUserRequest.php │ │ │ ├── UpdateArticleRequest.php │ │ │ └── UpdateUserRequest.php │ └── Resources │ │ └── Api │ │ ├── ArticleResource.php │ │ ├── ArticlesCollection.php │ │ ├── BaseUserResource.php │ │ ├── CommentResource.php │ │ ├── CommentsCollection.php │ │ ├── ProfileResource.php │ │ ├── TagResource.php │ │ ├── TagsCollection.php │ │ └── UserResource.php ├── Jwt │ ├── Builder.php │ ├── Generator.php │ ├── Parser.php │ ├── Token.php │ └── Validator.php ├── Models │ ├── Article.php │ ├── Comment.php │ ├── Tag.php │ └── User.php ├── Policies │ ├── ArticlePolicy.php │ └── CommentPolicy.php └── Providers │ ├── AppServiceProvider.php │ ├── AuthServiceProvider.php │ ├── BroadcastServiceProvider.php │ ├── EventServiceProvider.php │ └── RouteServiceProvider.php ├── artisan ├── bootstrap ├── app.php └── cache │ └── .gitignore ├── composer.json ├── composer.lock ├── config ├── app.php ├── auth.php ├── broadcasting.php ├── cache.php ├── cors.php ├── database.php ├── filesystems.php ├── hashing.php ├── jwt.php ├── l5-swagger.php ├── logging.php ├── mail.php ├── queue.php ├── sanctum.php ├── services.php ├── session.php └── view.php ├── database ├── .gitignore ├── factories │ ├── ArticleFactory.php │ ├── CommentFactory.php │ ├── TagFactory.php │ └── UserFactory.php ├── migrations │ ├── 2014_10_12_000000_create_users_table.php │ ├── 2014_10_12_100000_create_password_resets_table.php │ ├── 2019_08_19_000000_create_failed_jobs_table.php │ ├── 2019_12_14_000001_create_personal_access_tokens_table.php │ ├── 2021_05_21_130644_add_fields_to_users_table.php │ ├── 2021_05_23_123208_create_user_follower_table.php │ ├── 2021_05_23_150828_create_articles_table.php │ ├── 2021_05_23_150839_create_comments_table.php │ ├── 2021_05_23_150848_create_tags_table.php │ ├── 2021_05_23_151511_create_article_tag_table.php │ └── 2021_05_23_152011_create_article_favorite_table.php └── seeders │ └── DatabaseSeeder.php ├── docker-compose.yml ├── lang └── en │ ├── auth.php │ ├── models.php │ ├── pagination.php │ ├── passwords.php │ └── validation.php ├── package.json ├── phpstan-baseline.neon ├── phpstan.neon ├── phpunit.xml ├── public ├── .htaccess ├── favicon.ico ├── index.php └── robots.txt ├── resources ├── css │ └── app.css ├── js │ ├── app.js │ └── bootstrap.js └── views │ ├── vendor │ └── l5-swagger │ │ ├── .gitkeep │ │ └── index.blade.php │ └── welcome.blade.php ├── routes ├── api.php ├── channels.php ├── console.php └── web.php ├── storage ├── api-docs │ └── .gitignore ├── app │ ├── .gitignore │ └── public │ │ └── .gitignore ├── framework │ ├── .gitignore │ ├── cache │ │ ├── .gitignore │ │ └── data │ │ │ └── .gitignore │ ├── sessions │ │ └── .gitignore │ ├── testing │ │ └── .gitignore │ └── views │ │ └── .gitignore └── logs │ └── .gitignore ├── tests ├── CreatesApplication.php ├── Feature │ ├── Api │ │ ├── Article │ │ │ ├── ArticleFeedTest.php │ │ │ ├── CreateArticleTest.php │ │ │ ├── DeleteArticleTest.php │ │ │ ├── ListArticlesTest.php │ │ │ ├── ShowArticleTest.php │ │ │ └── UpdateArticleTest.php │ │ ├── Auth │ │ │ ├── JwtGuardTest.php │ │ │ ├── LoginTest.php │ │ │ └── RegisterTest.php │ │ ├── Comments │ │ │ ├── CreateCommentTest.php │ │ │ ├── DeleteCommentTest.php │ │ │ └── ListCommentsTest.php │ │ ├── Favorites │ │ │ ├── AddFavoritesTest.php │ │ │ └── RemoveFavoritesTest.php │ │ ├── Profile │ │ │ ├── FollowProfileTest.php │ │ │ ├── ShowProfileTest.php │ │ │ └── UnfollowProfileTest.php │ │ ├── TagsTest.php │ │ └── User │ │ │ ├── ShowUserTest.php │ │ │ └── UpdateUserTest.php │ └── Jwt │ │ └── JwtValidatorTest.php ├── TestCase.php └── Unit │ └── Jwt │ └── JwtParserTest.php └── webpack.mix.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | indent_style = space 8 | indent_size = 4 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | 14 | [*.{yml,yaml}] 15 | indent_size = 2 16 | 17 | [docker-compose.yml] 18 | indent_size = 4 19 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | APP_NAME="Laravel Realworld Example App" 2 | APP_ENV=local 3 | APP_KEY= 4 | APP_DEBUG=true 5 | APP_URL=http://localhost 6 | APP_PORT=3000 7 | 8 | LOG_CHANNEL=stack 9 | LOG_DEPRECATIONS_CHANNEL=null 10 | LOG_LEVEL=debug 11 | 12 | DB_CONNECTION=pgsql 13 | DB_HOST=pgsql 14 | DB_PORT=5432 15 | DB_DATABASE=laravel-realworld 16 | DB_USERNAME=sail 17 | DB_PASSWORD=password 18 | 19 | BROADCAST_DRIVER=log 20 | CACHE_DRIVER=file 21 | FILESYSTEM_DISK=local 22 | QUEUE_CONNECTION=sync 23 | SESSION_DRIVER=file 24 | SESSION_LIFETIME=120 25 | 26 | MEMCACHED_HOST=127.0.0.1 27 | 28 | REDIS_HOST=127.0.0.1 29 | REDIS_PASSWORD=null 30 | REDIS_PORT=6379 31 | 32 | MAIL_MAILER=smtp 33 | MAIL_HOST=mailhog 34 | MAIL_PORT=1025 35 | MAIL_USERNAME=null 36 | MAIL_PASSWORD=null 37 | MAIL_ENCRYPTION=null 38 | MAIL_FROM_ADDRESS="hello@example.com" 39 | MAIL_FROM_NAME="${APP_NAME}" 40 | 41 | AWS_ACCESS_KEY_ID= 42 | AWS_SECRET_ACCESS_KEY= 43 | AWS_DEFAULT_REGION=us-east-1 44 | AWS_BUCKET= 45 | AWS_USE_PATH_STYLE_ENDPOINT=false 46 | 47 | PUSHER_APP_ID= 48 | PUSHER_APP_KEY= 49 | PUSHER_APP_SECRET= 50 | PUSHER_APP_CLUSTER=mt1 51 | 52 | MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" 53 | MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" 54 | 55 | L5_SWAGGER_GENERATE_ALWAYS=true 56 | SAIL_XDEBUG_MODE=develop,debug 57 | SAIL_SKIP_CHECKS=true 58 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | 3 | *.blade.php diff=html 4 | *.css diff=css 5 | *.html diff=html 6 | *.md diff=markdown 7 | *.php diff=php 8 | 9 | /.github export-ignore 10 | CHANGELOG.md export-ignore 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /public/hot 3 | /public/storage 4 | /storage/*.key 5 | /vendor 6 | .env 7 | .env.backup 8 | .phpunit.result.cache 9 | Homestead.json 10 | Homestead.yaml 11 | npm-debug.log 12 | yarn-error.log 13 | /.idea 14 | /.vscode 15 | /.phpstorm.meta.php 16 | /_ide_helper.php 17 | /_ide_helper_models.php 18 | /coverage.xml 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 f1amy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![Laravel RealWorld Example App](.github/readme/logo.png) 2 | 3 | [![RealWorld: Backend](https://img.shields.io/badge/RealWorld-Backend-blueviolet.svg)](https://github.com/gothinkster/realworld) 4 | [![Tests: status](https://github.com/f1amy/laravel-realworld-example-app/actions/workflows/tests.yml/badge.svg)](https://github.com/f1amy/laravel-realworld-example-app/actions/workflows/tests.yml) 5 | [![Coverage: percent](https://codecov.io/gh/f1amy/laravel-realworld-example-app/branch/main/graph/badge.svg)](https://codecov.io/gh/f1amy/laravel-realworld-example-app) 6 | [![Static Analysis: status](https://github.com/f1amy/laravel-realworld-example-app/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/f1amy/laravel-realworld-example-app/actions/workflows/static-analysis.yml) 7 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellowgreen.svg)](https://opensource.org/licenses/MIT) 8 | 9 | > Example of a PHP-based Laravel application containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the [RealWorld](https://github.com/gothinkster/realworld) API spec. 10 | 11 | This codebase was created to demonstrate a backend application built with [Laravel framework](https://laravel.com/) including RESTful services, CRUD operations, authentication, routing, pagination, and more. 12 | 13 | We've gone to great lengths to adhere to the **Laravel framework** community style guides & best practices. 14 | 15 | For more information on how to this works with other frontends/backends, head over to the [RealWorld](https://github.com/gothinkster/realworld) repo. 16 | 17 | ## How it works 18 | 19 | The API is built with [Laravel](https://laravel.com/), making the most of the framework's features out-of-the-box. 20 | 21 | The application is using a custom JWT auth implementation: [`app/Jwt`](./app/Jwt). 22 | 23 | ## Getting started 24 | 25 | The preferred way of setting up the project is using [Laravel Sail](https://laravel.com/docs/sail), 26 | for that you'll need [Docker](https://docs.docker.com/get-docker/) under Linux / macOS (or Windows WSL2). 27 | 28 | ### Installation 29 | 30 | Clone the repository and change directory: 31 | 32 | git clone https://github.com/f1amy/laravel-realworld-example-app.git 33 | cd laravel-realworld-example-app 34 | 35 | Install dependencies (if you have `composer` locally): 36 | 37 | composer create-project 38 | 39 | Alternatively you can do the same with Docker: 40 | 41 | docker run --rm -it \ 42 | --volume $PWD:/app \ 43 | --user $(id -u):$(id -g) \ 44 | composer create-project 45 | 46 | Start the containers with PHP application and PostgreSQL database: 47 | 48 | ./vendor/bin/sail up -d 49 | 50 | (Optional) Configure a Bash alias for `sail` command: 51 | 52 | alias sail='[ -f sail ] && bash sail || bash vendor/bin/sail' 53 | 54 | Migrate the database with seeding: 55 | 56 | sail artisan migrate --seed 57 | 58 | ## Usage 59 | 60 | The API is available at `http://localhost:3000/api` (You can change the `APP_PORT` in `.env` file). 61 | 62 | ### Run tests 63 | 64 | sail artisan test 65 | 66 | ### Run PHPStan static analysis 67 | 68 | sail php ./vendor/bin/phpstan 69 | 70 | ### OpenAPI specification (not ready yet) 71 | 72 | Swagger UI will be live at [http://localhost:3000/api/documentation](http://localhost:3000/api/documentation). 73 | 74 | For now, please visit the specification [here](https://github.com/gothinkster/realworld/tree/main/api). 75 | 76 | ## Contributions 77 | 78 | Feedback, suggestions, and improvements are welcome, feel free to contribute. 79 | 80 | ## License 81 | 82 | The MIT License (MIT). Please see [`LICENSE`](./LICENSE) for more information. 83 | -------------------------------------------------------------------------------- /app/Auth/JwtGuard.php: -------------------------------------------------------------------------------- 1 | request = $request; 49 | $this->provider = $provider; 50 | $this->inputKey = $inputKey; 51 | } 52 | 53 | /** 54 | * Get the currently authenticated user. 55 | * 56 | * @return \Illuminate\Contracts\Auth\Authenticatable|null 57 | */ 58 | public function user() 59 | { 60 | // If we've already retrieved the user for the current request we can just 61 | // return it back immediately. We do not want to fetch the user data on 62 | // every call to this method because that would be tremendously slow. 63 | if (! is_null($this->user)) { 64 | return $this->user; 65 | } 66 | 67 | $user = null; 68 | 69 | $token = $this->getTokenForRequest(); 70 | 71 | if (! empty($token) && is_string($token)) { 72 | try { 73 | $jwt = Jwt\Parser::parse($token); 74 | } catch (JwtParseException | JsonException) { 75 | $jwt = null; 76 | } 77 | 78 | if ($this->validate([$this->inputKey => $jwt])) { 79 | /** @var \App\Contracts\JwtTokenInterface $jwt */ 80 | $user = $this->provider->retrieveById( 81 | $jwt->getSubject() 82 | ); 83 | } 84 | } 85 | 86 | return $this->user = $user; 87 | } 88 | 89 | /** 90 | * Validate a user's credentials. 91 | * 92 | * @param array $credentials 93 | * @return bool 94 | */ 95 | public function validate(array $credentials = []) 96 | { 97 | if (empty($credentials[$this->inputKey])) { 98 | return false; 99 | } 100 | 101 | $token = $credentials[$this->inputKey]; 102 | 103 | if (! $token instanceof JwtTokenInterface) { 104 | return false; 105 | } 106 | 107 | return Jwt\Validator::validate($token); 108 | } 109 | 110 | /** 111 | * Get the token for the current request. 112 | * 113 | * @return mixed|null 114 | */ 115 | public function getTokenForRequest() 116 | { 117 | $token = $this->jwtToken(); 118 | 119 | if (empty($token)) { 120 | $token = $this->request->query($this->inputKey); 121 | } 122 | 123 | if (empty($token)) { 124 | $token = $this->request->input($this->inputKey); 125 | } 126 | 127 | return $token; 128 | } 129 | 130 | /** 131 | * Get the JWT token from the request headers. 132 | * 133 | * @return string|null 134 | */ 135 | public function jwtToken(): ?string 136 | { 137 | /** @var string $header */ 138 | $header = $this->request->header('Authorization', ''); 139 | 140 | if (Str::startsWith($header, 'Token ')) { 141 | return Str::substr($header, 6); 142 | } 143 | 144 | return null; 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /app/Console/Kernel.php: -------------------------------------------------------------------------------- 1 | command('inspire')->hourly(); 22 | } 23 | 24 | /** 25 | * Register the commands for the application. 26 | * 27 | * @return void 28 | */ 29 | protected function commands() 30 | { 31 | $this->load(__DIR__.'/Commands'); 32 | 33 | require base_path('routes/console.php'); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /app/Contracts/JwtBuilderInterface.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | public function getDefaultHeaders(): array; 15 | 16 | /** 17 | * Get a copy of headers set on token. 18 | * 19 | * @return \Illuminate\Support\Collection 20 | */ 21 | public function headers(): Collection; 22 | 23 | /** 24 | * Get a copy of claims set on token. 25 | * 26 | * @return \Illuminate\Support\Collection 27 | */ 28 | public function claims(): Collection; 29 | 30 | /** 31 | * Get saved user-supplied signature. 32 | * 33 | * @return string|null 34 | */ 35 | public function getUserSignature(): ?string; 36 | 37 | /** 38 | * Put value to payload under a key. 39 | * 40 | * @param string $key 41 | * @param mixed $value 42 | */ 43 | public function putToPayload(string $key, mixed $value): void; 44 | 45 | /** 46 | * Put value to header under a key. 47 | * 48 | * @param string $key 49 | * @param mixed $value 50 | */ 51 | public function putToHeader(string $key, mixed $value): void; 52 | 53 | /** 54 | * Set user-supplied signature. 55 | * 56 | * @param string $signature 57 | */ 58 | public function setUserSignature(string $signature): void; 59 | 60 | /** 61 | * Get subject key. 62 | * 63 | * @return mixed 64 | */ 65 | public function getSubject(): mixed; 66 | 67 | /** 68 | * Get expiration timestamp. 69 | * 70 | * @return int 71 | */ 72 | public function getExpiration(): int; 73 | } 74 | -------------------------------------------------------------------------------- /app/Contracts/JwtValidatorInterface.php: -------------------------------------------------------------------------------- 1 | , LogLevel::*> 20 | */ 21 | protected $levels = [ 22 | // 23 | ]; 24 | 25 | /** 26 | * A list of the exception types that are not reported. 27 | * 28 | * @var array> 29 | */ 30 | protected $dontReport = [ 31 | // 32 | ]; 33 | 34 | /** 35 | * A list of the inputs that are never flashed to the session on validation exceptions. 36 | * 37 | * @var array 38 | */ 39 | protected $dontFlash = [ 40 | 'current_password', 41 | 'password', 42 | 'password_confirmation', 43 | ]; 44 | 45 | /** 46 | * Register the exception handling callbacks for the application. 47 | * 48 | * @return void 49 | */ 50 | public function register() 51 | { 52 | $this->renderable(function (NotFoundHttpException $e) { 53 | if ($e->getPrevious() instanceof ModelNotFoundException) { 54 | return response()->json([ 55 | 'message' => trans('models.resource.404'), 56 | ], 404); 57 | } 58 | 59 | return null; 60 | }); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/Exceptions/JwtParseException.php: -------------------------------------------------------------------------------- 1 | 29 | */ 30 | public function list(ArticleListRequest $request) 31 | { 32 | $filter = collect($request->validated()); 33 | 34 | $limit = $this->getLimit($filter); 35 | $offset = $this->getOffset($filter); 36 | 37 | $list = Article::list($limit, $offset); 38 | 39 | if ($tag = $filter->get('tag')) { 40 | $list->havingTag($tag); 41 | } 42 | 43 | if ($authorName = $filter->get('author')) { 44 | $list->ofAuthor($authorName); 45 | } 46 | 47 | if ($userName = $filter->get('favorited')) { 48 | $list->favoredByUser($userName); 49 | } 50 | 51 | return new ArticlesCollection($list->get()); 52 | } 53 | 54 | /** 55 | * Display article feed for the user. 56 | * 57 | * @param \App\Http\Requests\Api\FeedRequest $request 58 | * @return \App\Http\Resources\Api\ArticlesCollection
59 | */ 60 | public function feed(FeedRequest $request) 61 | { 62 | $filter = collect($request->validated()); 63 | 64 | $limit = $this->getLimit($filter); 65 | $offset = $this->getOffset($filter); 66 | 67 | $feed = Article::list($limit, $offset) 68 | ->followedAuthorsOf($request->user()); 69 | 70 | return new ArticlesCollection($feed->get()); 71 | } 72 | 73 | /** 74 | * Store a newly created resource in storage. 75 | * 76 | * @param \App\Http\Requests\Api\NewArticleRequest $request 77 | * @return \Illuminate\Http\JsonResponse 78 | */ 79 | public function create(NewArticleRequest $request) 80 | { 81 | /** @var \App\Models\User $user */ 82 | $user = $request->user(); 83 | 84 | $attributes = $request->validated(); 85 | $attributes['author_id'] = $user->getKey(); 86 | 87 | $tags = Arr::pull($attributes, 'tagList'); 88 | $article = Article::create($attributes); 89 | 90 | if (is_array($tags)) { 91 | $article->attachTags($tags); 92 | } 93 | 94 | return (new ArticleResource($article)) 95 | ->response() 96 | ->setStatusCode(201); 97 | } 98 | 99 | /** 100 | * Display the specified resource. 101 | * 102 | * @param string $slug 103 | * @return \App\Http\Resources\Api\ArticleResource 104 | */ 105 | public function show(string $slug) 106 | { 107 | $article = Article::whereSlug($slug) 108 | ->firstOrFail(); 109 | 110 | return new ArticleResource($article); 111 | } 112 | 113 | /** 114 | * Update the specified resource in storage. 115 | * 116 | * @param \App\Http\Requests\Api\UpdateArticleRequest $request 117 | * @param string $slug 118 | * @return \App\Http\Resources\Api\ArticleResource 119 | * @throws \Illuminate\Auth\Access\AuthorizationException 120 | */ 121 | public function update(UpdateArticleRequest $request, string $slug) 122 | { 123 | $article = Article::whereSlug($slug) 124 | ->firstOrFail(); 125 | 126 | $this->authorize('update', $article); 127 | 128 | $article->update($request->validated()); 129 | 130 | return new ArticleResource($article); 131 | } 132 | 133 | /** 134 | * Remove the specified resource from storage. 135 | * 136 | * @param string $slug 137 | * @return \Illuminate\Http\JsonResponse 138 | * @throws \Illuminate\Auth\Access\AuthorizationException 139 | */ 140 | public function delete(string $slug) 141 | { 142 | $article = Article::whereSlug($slug) 143 | ->firstOrFail(); 144 | 145 | $this->authorize('delete', $article); 146 | 147 | $article->delete(); // cascade 148 | 149 | return response()->json([ 150 | 'message' => trans('models.article.deleted'), 151 | ]); 152 | } 153 | 154 | /** 155 | * Get limit from filter. 156 | * 157 | * @param \Illuminate\Support\Collection $filter 158 | * @return int 159 | */ 160 | private function getLimit(Collection $filter): int 161 | { 162 | return (int) ($filter['limit'] ?? static::FILTER_LIMIT); 163 | } 164 | 165 | /** 166 | * Get offset from filter. 167 | * 168 | * @param \Illuminate\Support\Collection $filter 169 | * @return int 170 | */ 171 | private function getOffset(Collection $filter): int 172 | { 173 | return (int) ($filter['offset'] ?? static::FILTER_OFFSET); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /app/Http/Controllers/Api/Articles/CommentsController.php: -------------------------------------------------------------------------------- 1 | 19 | */ 20 | public function list(string $slug) 21 | { 22 | $article = Article::whereSlug($slug) 23 | ->firstOrFail(); 24 | 25 | return new CommentsCollection($article->comments); 26 | } 27 | 28 | /** 29 | * Store a newly created resource in storage. 30 | * 31 | * @param \App\Http\Requests\Api\NewCommentRequest $request 32 | * @param string $slug 33 | * @return \Illuminate\Http\JsonResponse 34 | */ 35 | public function create(NewCommentRequest $request, string $slug) 36 | { 37 | $article = Article::whereSlug($slug) 38 | ->firstOrFail(); 39 | 40 | /** @var \App\Models\User $user */ 41 | $user = $request->user(); 42 | 43 | $comment = Comment::create([ 44 | 'article_id' => $article->getKey(), 45 | 'author_id' => $user->getKey(), 46 | 'body' => $request->input('comment.body'), 47 | ]); 48 | 49 | return (new CommentResource($comment)) 50 | ->response() 51 | ->setStatusCode(201); 52 | } 53 | 54 | /** 55 | * Remove the specified resource from storage. 56 | * 57 | * @param string $slug 58 | * @param mixed $id 59 | * @return \Illuminate\Http\JsonResponse 60 | * @throws \Illuminate\Auth\Access\AuthorizationException 61 | */ 62 | public function delete(string $slug, $id) 63 | { 64 | $article = Article::whereSlug($slug) 65 | ->firstOrFail(); 66 | 67 | $comment = $article->comments() 68 | ->findOrFail((int) $id); 69 | 70 | $this->authorize('delete', $comment); 71 | 72 | $comment->delete(); 73 | 74 | return response()->json([ 75 | 'message' => trans('models.comment.deleted'), 76 | ]); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /app/Http/Controllers/Api/Articles/FavoritesController.php: -------------------------------------------------------------------------------- 1 | firstOrFail(); 23 | 24 | /** @var \App\Models\User $user */ 25 | $user = $request->user(); 26 | 27 | $user->favorites()->syncWithoutDetaching($article); 28 | 29 | return new ArticleResource($article); 30 | } 31 | 32 | /** 33 | * Remove article from user's favorites. 34 | * 35 | * @param \Illuminate\Http\Request $request 36 | * @param string $slug 37 | * @return \App\Http\Resources\Api\ArticleResource 38 | */ 39 | public function remove(Request $request, string $slug) 40 | { 41 | $article = Article::whereSlug($slug) 42 | ->firstOrFail(); 43 | 44 | /** @var \App\Models\User $user */ 45 | $user = $request->user(); 46 | 47 | $user->favorites()->detach($article); 48 | 49 | return new ArticleResource($article); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /app/Http/Controllers/Api/AuthController.php: -------------------------------------------------------------------------------- 1 | validated(); 24 | 25 | $attributes['password'] = Hash::make($attributes['password']); 26 | 27 | $user = User::create($attributes); 28 | 29 | return (new UserResource($user)) 30 | ->response() 31 | ->setStatusCode(201); 32 | } 33 | 34 | /** 35 | * Login existing user. 36 | * 37 | * @param \App\Http\Requests\Api\LoginRequest $request 38 | * @return \App\Http\Resources\Api\UserResource|\Illuminate\Http\JsonResponse 39 | */ 40 | public function login(LoginRequest $request) 41 | { 42 | Auth::shouldUse('web'); 43 | 44 | if (Auth::attempt($request->validated())) { 45 | return new UserResource(Auth::user()); 46 | } 47 | 48 | return response()->json([ 49 | 'message' => trans('validation.invalid'), 50 | 'errors' => [ 51 | 'user' => [trans('auth.failed')], 52 | ], 53 | ], 422); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /app/Http/Controllers/Api/ProfileController.php: -------------------------------------------------------------------------------- 1 | firstOrFail(); 22 | 23 | return new ProfileResource($profile); 24 | } 25 | 26 | /** 27 | * Follow an author. 28 | * 29 | * @param \Illuminate\Http\Request $request 30 | * @param string $username 31 | * @return \App\Http\Resources\Api\ProfileResource 32 | */ 33 | public function follow(Request $request, string $username) 34 | { 35 | $profile = User::whereUsername($username) 36 | ->firstOrFail(); 37 | 38 | $profile->followers() 39 | ->syncWithoutDetaching($request->user()); 40 | 41 | return new ProfileResource($profile); 42 | } 43 | 44 | /** 45 | * Unfollow an author. 46 | * 47 | * @param \Illuminate\Http\Request $request 48 | * @param string $username 49 | * @return \App\Http\Resources\Api\ProfileResource 50 | */ 51 | public function unfollow(Request $request, string $username) 52 | { 53 | $profile = User::whereUsername($username) 54 | ->firstOrFail(); 55 | 56 | $profile->followers()->detach($request->user()); 57 | 58 | return new ProfileResource($profile); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /app/Http/Controllers/Api/TagsController.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | public function list() 17 | { 18 | return new TagsCollection(Tag::all()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/Http/Controllers/Api/UserController.php: -------------------------------------------------------------------------------- 1 | user()); 20 | } 21 | 22 | /** 23 | * Update the specified resource in storage. 24 | * 25 | * @param \App\Http\Requests\Api\UpdateUserRequest $request 26 | * @return \App\Http\Resources\Api\UserResource|\Illuminate\Http\JsonResponse 27 | */ 28 | public function update(UpdateUserRequest $request) 29 | { 30 | if (empty($attrs = $request->validated())) { 31 | return response()->json([ 32 | 'message' => trans('validation.invalid'), 33 | 'errors' => [ 34 | 'any' => [trans('validation.required_at_least_one')], 35 | ], 36 | ], 422); 37 | } 38 | 39 | /** @var \App\Models\User $user */ 40 | $user = $request->user(); 41 | 42 | $user->update($attrs); 43 | 44 | return new UserResource($user); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/Http/Controllers/Controller.php: -------------------------------------------------------------------------------- 1 | 15 | */ 16 | protected $middleware = [ 17 | // \App\Http\Middleware\TrustHosts::class, 18 | \App\Http\Middleware\TrustProxies::class, 19 | \Illuminate\Http\Middleware\HandleCors::class, 20 | \App\Http\Middleware\PreventRequestsDuringMaintenance::class, 21 | \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, 22 | \App\Http\Middleware\TrimStrings::class, 23 | \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, 24 | ]; 25 | 26 | /** 27 | * The application's route middleware groups. 28 | * 29 | * @var array> 30 | */ 31 | protected $middlewareGroups = [ 32 | 'web' => [ 33 | \App\Http\Middleware\EncryptCookies::class, 34 | \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 35 | \Illuminate\Session\Middleware\StartSession::class, 36 | \Illuminate\View\Middleware\ShareErrorsFromSession::class, 37 | \App\Http\Middleware\VerifyCsrfToken::class, 38 | \Illuminate\Routing\Middleware\SubstituteBindings::class, 39 | ], 40 | 41 | 'api' => [ 42 | // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 43 | 'throttle:api', 44 | \Illuminate\Routing\Middleware\SubstituteBindings::class, 45 | ], 46 | ]; 47 | 48 | /** 49 | * The application's route middleware. 50 | * 51 | * These middleware may be assigned to groups or used individually. 52 | * 53 | * @var array 54 | */ 55 | protected $routeMiddleware = [ 56 | 'auth' => \App\Http\Middleware\Authenticate::class, 57 | 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 58 | 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class, 59 | 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 60 | 'can' => \Illuminate\Auth\Middleware\Authorize::class, 61 | 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 62 | 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 63 | 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 64 | 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 65 | 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 66 | ]; 67 | } 68 | -------------------------------------------------------------------------------- /app/Http/Middleware/Authenticate.php: -------------------------------------------------------------------------------- 1 | expectsJson()) { 18 | return route('login'); 19 | } 20 | 21 | return null; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /app/Http/Middleware/EncryptCookies.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | protected $except = [ 15 | // 16 | ]; 17 | } 18 | -------------------------------------------------------------------------------- /app/Http/Middleware/PreventRequestsDuringMaintenance.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | protected $except = [ 15 | // 16 | ]; 17 | } 18 | -------------------------------------------------------------------------------- /app/Http/Middleware/RedirectIfAuthenticated.php: -------------------------------------------------------------------------------- 1 | check()) { 26 | return redirect(RouteServiceProvider::HOME); 27 | } 28 | } 29 | 30 | return $next($request); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /app/Http/Middleware/TrimStrings.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | protected $except = [ 15 | 'current_password', 16 | 'password', 17 | 'password_confirmation', 18 | ]; 19 | } 20 | -------------------------------------------------------------------------------- /app/Http/Middleware/TrustHosts.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | public function hosts() 15 | { 16 | return [ 17 | $this->allSubdomainsOfApplicationUrl(), 18 | ]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/Http/Middleware/TrustProxies.php: -------------------------------------------------------------------------------- 1 | |string|null 14 | */ 15 | protected $proxies; 16 | 17 | /** 18 | * The headers that should be used to detect proxies. 19 | * 20 | * @var int 21 | */ 22 | protected $headers = 23 | Request::HEADER_X_FORWARDED_FOR | 24 | Request::HEADER_X_FORWARDED_HOST | 25 | Request::HEADER_X_FORWARDED_PORT | 26 | Request::HEADER_X_FORWARDED_PROTO | 27 | Request::HEADER_X_FORWARDED_AWS_ELB; 28 | } 29 | -------------------------------------------------------------------------------- /app/Http/Middleware/VerifyCsrfToken.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | protected $except = [ 15 | // 16 | ]; 17 | } 18 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/ArticleListRequest.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | public function rules() 13 | { 14 | return array_merge(parent::rules(), [ 15 | 'tag' => 'sometimes|string', 16 | 'author' => 'sometimes|string', 17 | 'favorited' => 'sometimes|string', 18 | ]); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/BaseArticleRequest.php: -------------------------------------------------------------------------------- 1 | input(); 21 | $title = Arr::get($input, 'article.title'); 22 | 23 | if (is_string($title)) { 24 | Arr::set($input, 'article.slug', Str::slug($title)); 25 | } else { 26 | Arr::forget($input, 'article.slug'); 27 | } 28 | 29 | $this->merge($input); 30 | } 31 | 32 | /** 33 | * Get the validation rules that apply to the request. 34 | * 35 | * @return array 36 | */ 37 | public function rules() 38 | { 39 | $article = Article::whereSlug($this->route('slug')) 40 | ->first(); 41 | 42 | $unique = Rule::unique('articles', 'slug'); 43 | if ($article !== null) { 44 | $unique->ignoreModel($article); 45 | } 46 | 47 | return [ 48 | 'title' => ['string', 'max:255'], 49 | 'slug' => ['string', 'max:255', $unique], 50 | 'description' => ['string', 'max:510'], 51 | 'body' => ['string'], 52 | ]; 53 | } 54 | 55 | /** 56 | * @return array 57 | */ 58 | public function validationData() 59 | { 60 | return Arr::wrap($this->input('article')); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/FeedRequest.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | public function rules() 15 | { 16 | return [ 17 | 'limit' => 'sometimes|integer|min:0', 18 | 'offset' => 'sometimes|integer|min:0', 19 | ]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/LoginRequest.php: -------------------------------------------------------------------------------- 1 | 14 | */ 15 | public function rules() 16 | { 17 | return [ 18 | 'email' => 'required|string|email', 19 | 'password' => 'required|string', 20 | ]; 21 | } 22 | 23 | /** 24 | * @return array 25 | */ 26 | public function validationData() 27 | { 28 | return Arr::wrap($this->input('user')); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/NewArticleRequest.php: -------------------------------------------------------------------------------- 1 | ['required'], 11 | 'slug' => ['required'], 12 | 'description' => ['required'], 13 | 'body' => ['required'], 14 | 'tagList' => 'sometimes|array', 15 | 'tagList.*' => 'required|string|max:255', 16 | ]); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/NewCommentRequest.php: -------------------------------------------------------------------------------- 1 | 14 | */ 15 | public function rules() 16 | { 17 | return [ 18 | 'body' => 'required|string', 19 | ]; 20 | } 21 | 22 | /** 23 | * @return array 24 | */ 25 | public function validationData() 26 | { 27 | return Arr::wrap($this->input('comment')); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/NewUserRequest.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | public function rules() 18 | { 19 | return [ 20 | 'username' => [ 21 | 'required', 'string', 'regex:' . User::REGEX_USERNAME, 22 | 'max:255', 'unique:users,username' 23 | ], 24 | 'email' => 'required|string|email|max:255|unique:users,email', 25 | 'password' => [ 26 | 'required', 'string', 'max:255', 27 | // we can set additional password requirements below 28 | Password::min(8), 29 | ], 30 | ]; 31 | } 32 | 33 | /** 34 | * @return array 35 | */ 36 | public function validationData() 37 | { 38 | return Arr::wrap($this->input('user')); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/UpdateArticleRequest.php: -------------------------------------------------------------------------------- 1 | ['required_without_all:description,body'], 11 | 'slug' => ['required_with:title'], 12 | 'description' => ['required_without_all:title,body'], 13 | 'body' => ['required_without_all:title,description'], 14 | ]); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /app/Http/Requests/Api/UpdateUserRequest.php: -------------------------------------------------------------------------------- 1 | 17 | */ 18 | public function rules() 19 | { 20 | /** @var \App\Models\User|null $user */ 21 | $user = $this->user(); 22 | 23 | if ($user === null) { 24 | throw new InvalidArgumentException('User not authenticated.'); 25 | } 26 | 27 | return [ 28 | 'username' => [ 29 | 'sometimes', 'string', 'max:255', 'regex:' . User::REGEX_USERNAME, 30 | Rule::unique('users', 'username') 31 | ->ignore($user->getKey()), 32 | ], 33 | 'email' => [ 34 | 'sometimes', 'string', 'email', 'max:255', 35 | Rule::unique('users', 'email') 36 | ->ignore($user->getKey()), 37 | ], 38 | 'bio' => 'sometimes|nullable|string', 39 | 'image' => 'sometimes|nullable|string|url', 40 | ]; 41 | } 42 | 43 | /** 44 | * @return array 45 | */ 46 | public function validationData() 47 | { 48 | return Arr::wrap($this->input('user')); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/ArticleResource.php: -------------------------------------------------------------------------------- 1 | 27 | */ 28 | public function toArray($request) 29 | { 30 | /** @var \App\Models\User|null $user */ 31 | $user = $request->user(); 32 | 33 | return [ 34 | 'slug' => $this->resource->slug, 35 | 'title' => $this->resource->title, 36 | 'description' => $this->resource->description, 37 | 'body' => $this->resource->body, 38 | 'tagList' => new TagsCollection($this->resource->tags), 39 | 'createdAt' => $this->resource->created_at, 40 | 'updatedAt' => $this->resource->updated_at, 41 | 'favorited' => $this->when($user !== null, fn() => 42 | $this->resource->favoredBy($user) 43 | ), 44 | 'favoritesCount' => $this->resource->favoredUsers->count(), 45 | 'author' => new ProfileResource($this->resource->author), 46 | ]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/ArticlesCollection.php: -------------------------------------------------------------------------------- 1 | $collection 12 | */ 13 | class ArticlesCollection extends ResourceCollection 14 | { 15 | /** 16 | * The "data" wrapper that should be applied. 17 | * 18 | * @var string|null 19 | */ 20 | public static $wrap = 'articles'; 21 | 22 | /** 23 | * The resource that this resource collects. 24 | * 25 | * @var string 26 | */ 27 | public $collects = ArticleResource::class; 28 | 29 | /** 30 | * Get additional data that should be returned with the resource array. 31 | * 32 | * @param \Illuminate\Http\Request $request 33 | * @return array 34 | */ 35 | public function with($request) 36 | { 37 | return [ 38 | 'articlesCount' => $this->collection->count(), 39 | ]; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/BaseUserResource.php: -------------------------------------------------------------------------------- 1 | 20 | */ 21 | public function toArray($request) 22 | { 23 | return [ 24 | 'username' => $this->resource->username, 25 | 'bio' => $this->resource->bio, 26 | 'image' => $this->resource->image, 27 | ]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/CommentResource.php: -------------------------------------------------------------------------------- 1 | 27 | */ 28 | public function toArray($request) 29 | { 30 | return [ 31 | 'id' => $this->resource->getKey(), 32 | 'createdAt' => $this->resource->created_at, 33 | 'updatedAt' => $this->resource->updated_at, 34 | 'body' => $this->resource->body, 35 | 'author' => new ProfileResource($this->resource->author), 36 | ]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/CommentsCollection.php: -------------------------------------------------------------------------------- 1 | $collection 12 | */ 13 | class CommentsCollection extends ResourceCollection 14 | { 15 | /** 16 | * The "data" wrapper that should be applied. 17 | * 18 | * @var string|null 19 | */ 20 | public static $wrap = 'comments'; 21 | 22 | /** 23 | * The resource that this resource collects. 24 | * 25 | * @var string 26 | */ 27 | public $collects = CommentResource::class; 28 | } 29 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/ProfileResource.php: -------------------------------------------------------------------------------- 1 | 19 | */ 20 | public function toArray($request) 21 | { 22 | /** @var \App\Models\User|null $user */ 23 | $user = $request->user(); 24 | 25 | return array_merge(parent::toArray($request), [ 26 | 'following' => $this->when($user !== null, fn() => 27 | $user->following($this->resource) 28 | ), 29 | ]); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/TagResource.php: -------------------------------------------------------------------------------- 1 | 20 | */ 21 | public function toArray($request) 22 | { 23 | return [ 24 | 'name' => $this->resource->name, 25 | ]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/TagsCollection.php: -------------------------------------------------------------------------------- 1 | $collection 12 | */ 13 | class TagsCollection extends ResourceCollection 14 | { 15 | /** 16 | * The "data" wrapper that should be applied. 17 | * 18 | * @var string|null 19 | */ 20 | public static $wrap = 'tags'; 21 | 22 | /** 23 | * The resource that this resource collects. 24 | * 25 | * @var string 26 | */ 27 | public $collects = TagResource::class; 28 | 29 | /** 30 | * Transform the resource collection into an array. 31 | * 32 | * @param \Illuminate\Http\Request $request 33 | * @return \Illuminate\Support\Collection 34 | */ 35 | public function toArray($request) 36 | { 37 | return $this->collection->pluck('name'); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/Http/Resources/Api/UserResource.php: -------------------------------------------------------------------------------- 1 | 21 | */ 22 | public function toArray($request) 23 | { 24 | return array_merge(parent::toArray($request), [ 25 | 'email' => $this->resource->email, 26 | 'token' => Jwt\Generator::token($this->resource), 27 | ]); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /app/Jwt/Builder.php: -------------------------------------------------------------------------------- 1 | jwt = new Token(); 16 | } 17 | 18 | public static function build(): JwtBuilderInterface 19 | { 20 | return new self(); 21 | } 22 | 23 | public function issuedAt(int $timestamp): JwtBuilderInterface 24 | { 25 | $this->jwt->putToPayload('iat', $timestamp); 26 | 27 | return $this; 28 | } 29 | 30 | public function expiresAt(int $timestamp): JwtBuilderInterface 31 | { 32 | $this->jwt->putToPayload('exp', $timestamp); 33 | 34 | return $this; 35 | } 36 | 37 | public function subject(mixed $identifier): JwtBuilderInterface 38 | { 39 | if ($identifier instanceof JwtSubjectInterface) { 40 | $identifier = $identifier->getJwtIdentifier(); 41 | } 42 | 43 | $this->jwt->putToPayload('sub', $identifier); 44 | 45 | return $this; 46 | } 47 | 48 | public function withClaim(string $key, mixed $value = null): JwtBuilderInterface 49 | { 50 | $this->jwt->putToPayload($key, $value); 51 | 52 | return $this; 53 | } 54 | 55 | public function withHeader(string $key, mixed $value = null): JwtBuilderInterface 56 | { 57 | $this->jwt->putToHeader($key, $value); 58 | 59 | return $this; 60 | } 61 | 62 | public function getToken(): JwtTokenInterface 63 | { 64 | return $this->jwt; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /app/Jwt/Generator.php: -------------------------------------------------------------------------------- 1 | addSeconds($expiresIn); 31 | 32 | $token = Builder::build() 33 | ->subject($user) 34 | ->issuedAt($now->getTimestamp()) 35 | ->expiresAt($expiresAt->getTimestamp()) 36 | ->getToken(); 37 | 38 | $parts = [ 39 | self::encodeData($token), 40 | base64_encode(self::signature($token)), 41 | ]; 42 | 43 | return implode('.', $parts); 44 | } 45 | 46 | /** 47 | * Encode JwtToken headers and payload. 48 | * 49 | * @param \App\Contracts\JwtTokenInterface $token 50 | * @return string 51 | */ 52 | private static function encodeData(JwtTokenInterface $token): string 53 | { 54 | $jsonParts = [ 55 | $token->headers()->toJson(), 56 | $token->claims()->toJson(), 57 | ]; 58 | 59 | $encoded = array_map('base64_encode', $jsonParts); 60 | 61 | return implode('.', $encoded); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/Jwt/Parser.php: -------------------------------------------------------------------------------- 1 | 39 | json_decode($part, true, 512, JSON_THROW_ON_ERROR), 40 | [$jsonHeader, $jsonPayload] 41 | ); 42 | 43 | [$header, $payload] = $jsonDecoded; 44 | 45 | return new Token($header, $payload, $signature); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /app/Jwt/Token.php: -------------------------------------------------------------------------------- 1 | */ 14 | private Collection $header; 15 | 16 | /** @var Collection */ 17 | private Collection $payload; 18 | 19 | /** 20 | * Token constructor. 21 | * 22 | * @param array|null $headers 23 | * @param array|null $claims 24 | * @param string|null $signature User-supplied signature 25 | */ 26 | public function __construct( 27 | array $headers = null, 28 | array $claims = null, 29 | string $signature = null) 30 | { 31 | $this->header = collect( 32 | array_merge($this->getDefaultHeaders(), $headers ?? []) 33 | ); 34 | $this->payload = collect($claims); 35 | $this->signature = $signature; 36 | } 37 | 38 | public function getDefaultHeaders(): array 39 | { 40 | $headers = config('jwt.headers'); 41 | 42 | return is_array($headers) ? $headers : []; 43 | } 44 | 45 | public function headers(): Collection 46 | { 47 | return clone $this->header; 48 | } 49 | 50 | public function claims(): Collection 51 | { 52 | return clone $this->payload; 53 | } 54 | 55 | public function getUserSignature(): ?string 56 | { 57 | return $this->signature; 58 | } 59 | 60 | public function putToPayload(string $key, mixed $value): void 61 | { 62 | $this->payload->put($key, $value); 63 | } 64 | 65 | public function putToHeader(string $key, mixed $value): void 66 | { 67 | $this->header->put($key, $value); 68 | } 69 | 70 | public function setUserSignature(string $signature): void 71 | { 72 | $this->signature = $signature; 73 | } 74 | 75 | public function getSubject(): mixed 76 | { 77 | return $this->payload->get('sub'); 78 | } 79 | 80 | public function getExpiration(): int 81 | { 82 | return (int) $this->payload->get('exp'); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /app/Jwt/Validator.php: -------------------------------------------------------------------------------- 1 | getUserSignature(); 15 | if ($signature === null) { 16 | return false; 17 | } 18 | if (!hash_equals(Generator::signature($token), $signature)) { 19 | return false; 20 | } 21 | 22 | $headers = $token->headers(); 23 | if ($headers->get('alg') !== 'HS256' 24 | || $headers->get('typ') !== 'JWT') { 25 | return false; 26 | } 27 | 28 | $expiresAt = $token->getExpiration(); 29 | if ($expiresAt === 0) { 30 | return false; 31 | } 32 | $expirationDate = Carbon::createFromTimestamp($expiresAt); 33 | $currentDate = Carbon::now(); 34 | if ($expirationDate->lessThan($currentDate)) { 35 | return false; 36 | } 37 | 38 | $subject = $token->getSubject(); 39 | if (User::whereKey($subject)->doesntExist()) { 40 | return false; 41 | } 42 | 43 | return true; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /app/Models/Comment.php: -------------------------------------------------------------------------------- 1 | 50 | */ 51 | public function article() 52 | { 53 | return $this->belongsTo(Article::class); 54 | } 55 | 56 | /** 57 | * Comment's author. 58 | * 59 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo 60 | */ 61 | public function author() 62 | { 63 | return $this->belongsTo(User::class); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /app/Models/Tag.php: -------------------------------------------------------------------------------- 1 | 44 | */ 45 | public function articles() 46 | { 47 | return $this->belongsToMany(Article::class); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/Policies/ArticlePolicy.php: -------------------------------------------------------------------------------- 1 | getKey() === $article->author->getKey(); 23 | } 24 | 25 | /** 26 | * Determine whether the user can delete the model. 27 | * 28 | * @param \App\Models\User $user 29 | * @param \App\Models\Article $article 30 | * @return bool 31 | */ 32 | public function delete(User $user, Article $article): bool 33 | { 34 | return $this->update($user, $article); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/Policies/CommentPolicy.php: -------------------------------------------------------------------------------- 1 | getKey() === $comment->author->getKey(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/Providers/AppServiceProvider.php: -------------------------------------------------------------------------------- 1 | 16 | */ 17 | protected $policies = [ 18 | // 'App\Models\Model' => 'App\Policies\ModelPolicy', 19 | ]; 20 | 21 | /** 22 | * Register any authentication / authorization services. 23 | * 24 | * @return void 25 | */ 26 | public function boot() 27 | { 28 | $this->registerPolicies(); 29 | 30 | Auth::extend('jwt', function ($app, $name, array $config) { 31 | $provider = Auth::createUserProvider($config['provider'] ?? null); 32 | 33 | if ($provider === null) { 34 | throw new InvalidArgumentException('Invalid UserProvider config specified.'); 35 | } 36 | 37 | return new JwtGuard($provider, $app['request'], $config['input_key'] ?? 'token'); 38 | }); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/Providers/BroadcastServiceProvider.php: -------------------------------------------------------------------------------- 1 | > 16 | */ 17 | protected $listen = [ 18 | /*Registered::class => [ 19 | SendEmailVerificationNotification::class, 20 | ],*/ 21 | ]; 22 | 23 | /** 24 | * Register any events for your application. 25 | * 26 | * @return void 27 | */ 28 | public function boot() 29 | { 30 | // 31 | } 32 | 33 | /** 34 | * Determine if events and listeners should be automatically discovered. 35 | * 36 | * @return bool 37 | */ 38 | public function shouldDiscoverEvents() 39 | { 40 | return false; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /app/Providers/RouteServiceProvider.php: -------------------------------------------------------------------------------- 1 | configureRateLimiting(); 30 | 31 | $this->routes(function () { 32 | Route::middleware('api') 33 | ->prefix('api') 34 | ->group(base_path('routes/api.php')); 35 | 36 | Route::middleware('web') 37 | ->group(base_path('routes/web.php')); 38 | }); 39 | } 40 | 41 | /** 42 | * Configure the rate limiters for the application. 43 | * 44 | * @return void 45 | */ 46 | protected function configureRateLimiting() 47 | { 48 | RateLimiter::for('api', function (Request $request) { 49 | return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); 50 | }); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /artisan: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | make(Illuminate\Contracts\Console\Kernel::class); 34 | 35 | $status = $kernel->handle( 36 | $input = new Symfony\Component\Console\Input\ArgvInput, 37 | new Symfony\Component\Console\Output\ConsoleOutput 38 | ); 39 | 40 | /* 41 | |-------------------------------------------------------------------------- 42 | | Shutdown The Application 43 | |-------------------------------------------------------------------------- 44 | | 45 | | Once Artisan has finished running, we will fire off the shutdown events 46 | | so that any final work may be done by the application before we shut 47 | | down the process. This is the last thing to happen to the request. 48 | | 49 | */ 50 | 51 | $kernel->terminate($input, $status); 52 | 53 | exit($status); 54 | -------------------------------------------------------------------------------- /bootstrap/app.php: -------------------------------------------------------------------------------- 1 | singleton( 30 | Illuminate\Contracts\Http\Kernel::class, 31 | App\Http\Kernel::class 32 | ); 33 | 34 | $app->singleton( 35 | Illuminate\Contracts\Console\Kernel::class, 36 | App\Console\Kernel::class 37 | ); 38 | 39 | $app->singleton( 40 | Illuminate\Contracts\Debug\ExceptionHandler::class, 41 | App\Exceptions\Handler::class 42 | ); 43 | 44 | /* 45 | |-------------------------------------------------------------------------- 46 | | Return The Application 47 | |-------------------------------------------------------------------------- 48 | | 49 | | This script returns the application instance. The instance is given to 50 | | the calling script so we can separate the building of the instances 51 | | from the actual running of the application and sending responses. 52 | | 53 | */ 54 | 55 | return $app; 56 | -------------------------------------------------------------------------------- /bootstrap/cache/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "f1amy/laravel-realworld-example-app", 3 | "type": "project", 4 | "description": "Laravel framework RealWorld backend implementation.", 5 | "keywords": ["laravel", "jwt", "crud", "demo-app", "realworld", "rest-api"], 6 | "homepage": "https://github.com/f1amy/laravel-realworld-example-app", 7 | "license": "MIT", 8 | "require": { 9 | "php": "^8.0.2", 10 | "ext-json": "*", 11 | "ext-pdo": "*", 12 | "darkaonline/l5-swagger": "^8.3", 13 | "guzzlehttp/guzzle": "^7.2", 14 | "laravel/framework": "^9.11", 15 | "laravel/sanctum": "^2.14.1", 16 | "laravel/tinker": "^2.7" 17 | }, 18 | "require-dev": { 19 | "barryvdh/laravel-ide-helper": "^2.12", 20 | "brianium/paratest": "^6.4", 21 | "fakerphp/faker": "^1.9.1", 22 | "laravel/sail": "^1.0.1", 23 | "mockery/mockery": "^1.4.4", 24 | "nunomaduro/collision": "^6.1", 25 | "nunomaduro/larastan": "^2.1", 26 | "phpstan/extension-installer": "^1.1", 27 | "phpstan/phpstan": "^1.4", 28 | "phpstan/phpstan-phpunit": "^1.0", 29 | "phpunit/phpunit": "^9.5.10", 30 | "roave/security-advisories": "dev-latest", 31 | "spatie/laravel-ignition": "^1.0" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "App\\": "app/", 36 | "Database\\Factories\\": "database/factories/", 37 | "Database\\Seeders\\": "database/seeders/" 38 | } 39 | }, 40 | "autoload-dev": { 41 | "psr-4": { 42 | "Tests\\": "tests/" 43 | } 44 | }, 45 | "scripts": { 46 | "post-autoload-dump": [ 47 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", 48 | "@php artisan package:discover --ansi" 49 | ], 50 | "post-update-cmd": [ 51 | "@php artisan vendor:publish --tag=laravel-assets --ansi --force", 52 | "[ $COMPOSER_DEV_MODE -eq 0 ] || $PHP_BINARY artisan ide-helper:generate -WHM", 53 | "[ $COMPOSER_DEV_MODE -eq 0 ] || $PHP_BINARY artisan ide-helper:meta" 54 | ], 55 | "post-root-package-install": [ 56 | "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" 57 | ], 58 | "post-create-project-cmd": [ 59 | "@php artisan key:generate --ansi" 60 | ] 61 | }, 62 | "extra": { 63 | "laravel": { 64 | "dont-discover": [] 65 | } 66 | }, 67 | "config": { 68 | "optimize-autoloader": true, 69 | "preferred-install": "dist", 70 | "sort-packages": true, 71 | "platform": { 72 | "php": "8.0.2" 73 | }, 74 | "allow-plugins": { 75 | "phpstan/extension-installer": true 76 | } 77 | }, 78 | "minimum-stability": "dev", 79 | "prefer-stable": true 80 | } 81 | -------------------------------------------------------------------------------- /config/auth.php: -------------------------------------------------------------------------------- 1 | [ 17 | 'guard' => 'api', 18 | 'passwords' => 'users', 19 | ], 20 | 21 | /* 22 | |-------------------------------------------------------------------------- 23 | | Authentication Guards 24 | |-------------------------------------------------------------------------- 25 | | 26 | | Next, you may define every authentication guard for your application. 27 | | Of course, a great default configuration has been defined for you 28 | | here which uses session storage and the Eloquent user provider. 29 | | 30 | | All authentication drivers have a user provider. This defines how the 31 | | users are actually retrieved out of your database or other storage 32 | | mechanisms used by this application to persist your user's data. 33 | | 34 | | Supported: "session", "jwt" 35 | | 36 | */ 37 | 38 | 'guards' => [ 39 | 'web' => [ 40 | 'driver' => 'session', 41 | 'provider' => 'users', 42 | ], 43 | 44 | 'api' => [ 45 | 'driver' => 'jwt', 46 | 'provider' => 'users', 47 | 'input_key' => 'token', 48 | ], 49 | ], 50 | 51 | /* 52 | |-------------------------------------------------------------------------- 53 | | User Providers 54 | |-------------------------------------------------------------------------- 55 | | 56 | | All authentication drivers have a user provider. This defines how the 57 | | users are actually retrieved out of your database or other storage 58 | | mechanisms used by this application to persist your user's data. 59 | | 60 | | If you have multiple user tables or models you may configure multiple 61 | | sources which represent each model / table. These sources may then 62 | | be assigned to any extra authentication guards you have defined. 63 | | 64 | | Supported: "database", "eloquent" 65 | | 66 | */ 67 | 68 | 'providers' => [ 69 | 'users' => [ 70 | 'driver' => 'eloquent', 71 | 'model' => App\Models\User::class, 72 | ], 73 | 74 | // 'users' => [ 75 | // 'driver' => 'database', 76 | // 'table' => 'users', 77 | // ], 78 | ], 79 | 80 | /* 81 | |-------------------------------------------------------------------------- 82 | | Resetting Passwords 83 | |-------------------------------------------------------------------------- 84 | | 85 | | You may specify multiple password reset configurations if you have more 86 | | than one user table or model in the application and you want to have 87 | | separate password reset settings based on the specific user types. 88 | | 89 | | The expire time is the number of minutes that each reset token will be 90 | | considered valid. This security feature keeps tokens short-lived so 91 | | they have less time to be guessed. You may change this as needed. 92 | | 93 | */ 94 | 95 | 'passwords' => [ 96 | 'users' => [ 97 | 'provider' => 'users', 98 | 'table' => 'password_resets', 99 | 'expire' => 60, 100 | 'throttle' => 60, 101 | ], 102 | ], 103 | 104 | /* 105 | |-------------------------------------------------------------------------- 106 | | Password Confirmation Timeout 107 | |-------------------------------------------------------------------------- 108 | | 109 | | Here you may define the amount of seconds before a password confirmation 110 | | times out and the user is prompted to re-enter their password via the 111 | | confirmation screen. By default, the timeout lasts for three hours. 112 | | 113 | */ 114 | 115 | 'password_timeout' => 10800, 116 | 117 | ]; 118 | -------------------------------------------------------------------------------- /config/broadcasting.php: -------------------------------------------------------------------------------- 1 | env('BROADCAST_DRIVER', 'null'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Broadcast Connections 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may define all of the broadcast connections that will be used 26 | | to broadcast events to other systems or over websockets. Samples of 27 | | each available type of connection are provided inside this array. 28 | | 29 | */ 30 | 31 | 'connections' => [ 32 | 33 | 'pusher' => [ 34 | 'driver' => 'pusher', 35 | 'key' => env('PUSHER_APP_KEY'), 36 | 'secret' => env('PUSHER_APP_SECRET'), 37 | 'app_id' => env('PUSHER_APP_ID'), 38 | 'options' => [ 39 | 'host' => env('PUSHER_HOST', 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com'), 40 | 'port' => env('PUSHER_PORT', 443), 41 | 'scheme' => env('PUSHER_SCHEME', 'https'), 42 | 'encrypted' => true, 43 | 'useTLS' => env('PUSHER_SCHEME', 'https') === 'https', 44 | ], 45 | 'client_options' => [ 46 | // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html 47 | ], 48 | ], 49 | 50 | 'ably' => [ 51 | 'driver' => 'ably', 52 | 'key' => env('ABLY_KEY'), 53 | ], 54 | 55 | 'redis' => [ 56 | 'driver' => 'redis', 57 | 'connection' => 'default', 58 | ], 59 | 60 | 'log' => [ 61 | 'driver' => 'log', 62 | ], 63 | 64 | 'null' => [ 65 | 'driver' => 'null', 66 | ], 67 | 68 | ], 69 | 70 | ]; 71 | -------------------------------------------------------------------------------- /config/cache.php: -------------------------------------------------------------------------------- 1 | env('CACHE_DRIVER', 'file'), 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Cache Stores 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may define all of the cache "stores" for your application as 26 | | well as their drivers. You may even define multiple stores for the 27 | | same cache driver to group types of items stored in your caches. 28 | | 29 | | Supported drivers: "apc", "array", "database", "file", 30 | | "memcached", "redis", "dynamodb", "octane", "null" 31 | | 32 | */ 33 | 34 | 'stores' => [ 35 | 36 | 'apc' => [ 37 | 'driver' => 'apc', 38 | ], 39 | 40 | 'array' => [ 41 | 'driver' => 'array', 42 | 'serialize' => false, 43 | ], 44 | 45 | 'database' => [ 46 | 'driver' => 'database', 47 | 'table' => 'cache', 48 | 'connection' => null, 49 | 'lock_connection' => null, 50 | ], 51 | 52 | 'file' => [ 53 | 'driver' => 'file', 54 | 'path' => storage_path('framework/cache/data'), 55 | ], 56 | 57 | 'memcached' => [ 58 | 'driver' => 'memcached', 59 | 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), 60 | 'sasl' => [ 61 | env('MEMCACHED_USERNAME'), 62 | env('MEMCACHED_PASSWORD'), 63 | ], 64 | 'options' => [ 65 | // Memcached::OPT_CONNECT_TIMEOUT => 2000, 66 | ], 67 | 'servers' => [ 68 | [ 69 | 'host' => env('MEMCACHED_HOST', '127.0.0.1'), 70 | 'port' => env('MEMCACHED_PORT', 11211), 71 | 'weight' => 100, 72 | ], 73 | ], 74 | ], 75 | 76 | 'redis' => [ 77 | 'driver' => 'redis', 78 | 'connection' => 'cache', 79 | 'lock_connection' => 'default', 80 | ], 81 | 82 | 'dynamodb' => [ 83 | 'driver' => 'dynamodb', 84 | 'key' => env('AWS_ACCESS_KEY_ID'), 85 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 86 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 87 | 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), 88 | 'endpoint' => env('DYNAMODB_ENDPOINT'), 89 | ], 90 | 91 | 'octane' => [ 92 | 'driver' => 'octane', 93 | ], 94 | 95 | ], 96 | 97 | /* 98 | |-------------------------------------------------------------------------- 99 | | Cache Key Prefix 100 | |-------------------------------------------------------------------------- 101 | | 102 | | When utilizing the APC, database, memcached, Redis, or DynamoDB cache 103 | | stores there might be other applications using the same cache. For 104 | | that reason, you may prefix every cache key to avoid collisions. 105 | | 106 | */ 107 | 108 | 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'), 109 | 110 | ]; 111 | -------------------------------------------------------------------------------- /config/cors.php: -------------------------------------------------------------------------------- 1 | ['api/*', 'sanctum/csrf-cookie'], 19 | 20 | 'allowed_methods' => ['*'], 21 | 22 | 'allowed_origins' => ['*'], 23 | 24 | 'allowed_origins_patterns' => [], 25 | 26 | 'allowed_headers' => ['Content-Type', 'X-Requested-With', 'Authorization'], 27 | 28 | 'exposed_headers' => [], 29 | 30 | 'max_age' => 864000, 31 | 32 | 'supports_credentials' => true, 33 | 34 | ]; 35 | -------------------------------------------------------------------------------- /config/filesystems.php: -------------------------------------------------------------------------------- 1 | env('FILESYSTEM_DISK', 'local'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Filesystem Disks 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure as many filesystem "disks" as you wish, and you 24 | | may even configure multiple disks of the same driver. Defaults have 25 | | been set up for each driver as an example of the required values. 26 | | 27 | | Supported Drivers: "local", "ftp", "sftp", "s3" 28 | | 29 | */ 30 | 31 | 'disks' => [ 32 | 33 | 'local' => [ 34 | 'driver' => 'local', 35 | 'root' => storage_path('app'), 36 | 'throw' => false, 37 | ], 38 | 39 | 'public' => [ 40 | 'driver' => 'local', 41 | 'root' => storage_path('app/public'), 42 | 'url' => env('APP_URL').'/storage', 43 | 'visibility' => 'public', 44 | 'throw' => false, 45 | ], 46 | 47 | 's3' => [ 48 | 'driver' => 's3', 49 | 'key' => env('AWS_ACCESS_KEY_ID'), 50 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 51 | 'region' => env('AWS_DEFAULT_REGION'), 52 | 'bucket' => env('AWS_BUCKET'), 53 | 'url' => env('AWS_URL'), 54 | 'endpoint' => env('AWS_ENDPOINT'), 55 | 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), 56 | 'throw' => false, 57 | ], 58 | 59 | ], 60 | 61 | /* 62 | |-------------------------------------------------------------------------- 63 | | Symbolic Links 64 | |-------------------------------------------------------------------------- 65 | | 66 | | Here you may configure the symbolic links that will be created when the 67 | | `storage:link` Artisan command is executed. The array keys should be 68 | | the locations of the links and the values should be their targets. 69 | | 70 | */ 71 | 72 | 'links' => [ 73 | public_path('storage') => storage_path('app/public'), 74 | ], 75 | 76 | ]; 77 | -------------------------------------------------------------------------------- /config/hashing.php: -------------------------------------------------------------------------------- 1 | 'bcrypt', 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Bcrypt Options 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Here you may specify the configuration options that should be used when 26 | | passwords are hashed using the Bcrypt algorithm. This will allow you 27 | | to control the amount of time it takes to hash the given password. 28 | | 29 | */ 30 | 31 | 'bcrypt' => [ 32 | 'rounds' => env('BCRYPT_ROUNDS', 10), 33 | ], 34 | 35 | /* 36 | |-------------------------------------------------------------------------- 37 | | Argon Options 38 | |-------------------------------------------------------------------------- 39 | | 40 | | Here you may specify the configuration options that should be used when 41 | | passwords are hashed using the Argon algorithm. These will allow you 42 | | to control the amount of time it takes to hash the given password. 43 | | 44 | */ 45 | 46 | 'argon' => [ 47 | 'memory' => 65536, 48 | 'threads' => 1, 49 | 'time' => 4, 50 | ], 51 | 52 | ]; 53 | -------------------------------------------------------------------------------- /config/jwt.php: -------------------------------------------------------------------------------- 1 | (int) env('JWT_EXPIRATION', 3600), // one hour 9 | 10 | /** 11 | * Default JWT headers. 12 | */ 13 | 'headers' => [ 14 | 'alg' => 'HS256', 15 | 'typ' => 'JWT', 16 | ], 17 | 18 | ]; 19 | -------------------------------------------------------------------------------- /config/logging.php: -------------------------------------------------------------------------------- 1 | env('LOG_CHANNEL', 'stack'), 21 | 22 | /* 23 | |-------------------------------------------------------------------------- 24 | | Deprecations Log Channel 25 | |-------------------------------------------------------------------------- 26 | | 27 | | This option controls the log channel that should be used to log warnings 28 | | regarding deprecated PHP and library features. This allows you to get 29 | | your application ready for upcoming major versions of dependencies. 30 | | 31 | */ 32 | 33 | 'deprecations' => [ 34 | 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), 35 | 'trace' => false, 36 | ], 37 | 38 | /* 39 | |-------------------------------------------------------------------------- 40 | | Log Channels 41 | |-------------------------------------------------------------------------- 42 | | 43 | | Here you may configure the log channels for your application. Out of 44 | | the box, Laravel uses the Monolog PHP logging library. This gives 45 | | you a variety of powerful log handlers / formatters to utilize. 46 | | 47 | | Available Drivers: "single", "daily", "slack", "syslog", 48 | | "errorlog", "monolog", 49 | | "custom", "stack" 50 | | 51 | */ 52 | 53 | 'channels' => [ 54 | 'stack' => [ 55 | 'driver' => 'stack', 56 | 'channels' => ['single'], 57 | 'ignore_exceptions' => false, 58 | ], 59 | 60 | 'single' => [ 61 | 'driver' => 'single', 62 | 'path' => storage_path('logs/laravel.log'), 63 | 'level' => env('LOG_LEVEL', 'debug'), 64 | ], 65 | 66 | 'daily' => [ 67 | 'driver' => 'daily', 68 | 'path' => storage_path('logs/laravel.log'), 69 | 'level' => env('LOG_LEVEL', 'debug'), 70 | 'days' => 14, 71 | ], 72 | 73 | 'slack' => [ 74 | 'driver' => 'slack', 75 | 'url' => env('LOG_SLACK_WEBHOOK_URL'), 76 | 'username' => 'Laravel Log', 77 | 'emoji' => ':boom:', 78 | 'level' => env('LOG_LEVEL', 'critical'), 79 | ], 80 | 81 | 'papertrail' => [ 82 | 'driver' => 'monolog', 83 | 'level' => env('LOG_LEVEL', 'debug'), 84 | 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class), 85 | 'handler_with' => [ 86 | 'host' => env('PAPERTRAIL_URL'), 87 | 'port' => env('PAPERTRAIL_PORT'), 88 | 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'), 89 | ], 90 | ], 91 | 92 | 'stderr' => [ 93 | 'driver' => 'monolog', 94 | 'level' => env('LOG_LEVEL', 'debug'), 95 | 'handler' => StreamHandler::class, 96 | 'formatter' => env('LOG_STDERR_FORMATTER'), 97 | 'with' => [ 98 | 'stream' => 'php://stderr', 99 | ], 100 | ], 101 | 102 | 'syslog' => [ 103 | 'driver' => 'syslog', 104 | 'level' => env('LOG_LEVEL', 'debug'), 105 | ], 106 | 107 | 'errorlog' => [ 108 | 'driver' => 'errorlog', 109 | 'level' => env('LOG_LEVEL', 'debug'), 110 | ], 111 | 112 | 'null' => [ 113 | 'driver' => 'monolog', 114 | 'handler' => NullHandler::class, 115 | ], 116 | 117 | 'emergency' => [ 118 | 'path' => storage_path('logs/laravel.log'), 119 | ], 120 | ], 121 | 122 | ]; 123 | -------------------------------------------------------------------------------- /config/mail.php: -------------------------------------------------------------------------------- 1 | env('MAIL_MAILER', 'smtp'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Mailer Configurations 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure all of the mailers used by your application plus 24 | | their respective settings. Several examples have been configured for 25 | | you and you are free to add your own as your application requires. 26 | | 27 | | Laravel supports a variety of mail "transport" drivers to be used while 28 | | sending an e-mail. You will specify which one you are using for your 29 | | mailers below. You are free to add additional mailers as required. 30 | | 31 | | Supported: "smtp", "sendmail", "mailgun", "ses", 32 | | "postmark", "log", "array", "failover" 33 | | 34 | */ 35 | 36 | 'mailers' => [ 37 | 'smtp' => [ 38 | 'transport' => 'smtp', 39 | 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), 40 | 'port' => env('MAIL_PORT', 587), 41 | 'encryption' => env('MAIL_ENCRYPTION', 'tls'), 42 | 'username' => env('MAIL_USERNAME'), 43 | 'password' => env('MAIL_PASSWORD'), 44 | 'timeout' => null, 45 | 'local_domain' => env('MAIL_EHLO_DOMAIN'), 46 | ], 47 | 48 | 'ses' => [ 49 | 'transport' => 'ses', 50 | ], 51 | 52 | 'mailgun' => [ 53 | 'transport' => 'mailgun', 54 | ], 55 | 56 | 'postmark' => [ 57 | 'transport' => 'postmark', 58 | ], 59 | 60 | 'sendmail' => [ 61 | 'transport' => 'sendmail', 62 | 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'), 63 | ], 64 | 65 | 'log' => [ 66 | 'transport' => 'log', 67 | 'channel' => env('MAIL_LOG_CHANNEL'), 68 | ], 69 | 70 | 'array' => [ 71 | 'transport' => 'array', 72 | ], 73 | 74 | 'failover' => [ 75 | 'transport' => 'failover', 76 | 'mailers' => [ 77 | 'smtp', 78 | 'log', 79 | ], 80 | ], 81 | ], 82 | 83 | /* 84 | |-------------------------------------------------------------------------- 85 | | Global "From" Address 86 | |-------------------------------------------------------------------------- 87 | | 88 | | You may wish for all e-mails sent by your application to be sent from 89 | | the same address. Here, you may specify a name and address that is 90 | | used globally for all e-mails that are sent by your application. 91 | | 92 | */ 93 | 94 | 'from' => [ 95 | 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 96 | 'name' => env('MAIL_FROM_NAME', 'Example'), 97 | ], 98 | 99 | /* 100 | |-------------------------------------------------------------------------- 101 | | Markdown Mail Settings 102 | |-------------------------------------------------------------------------- 103 | | 104 | | If you are using Markdown based email rendering, you may configure your 105 | | theme and component paths here, allowing you to customize the design 106 | | of the emails. Or, you may simply stick with the Laravel defaults! 107 | | 108 | */ 109 | 110 | 'markdown' => [ 111 | 'theme' => 'default', 112 | 113 | 'paths' => [ 114 | resource_path('views/vendor/mail'), 115 | ], 116 | ], 117 | 118 | ]; 119 | -------------------------------------------------------------------------------- /config/queue.php: -------------------------------------------------------------------------------- 1 | env('QUEUE_CONNECTION', 'sync'), 17 | 18 | /* 19 | |-------------------------------------------------------------------------- 20 | | Queue Connections 21 | |-------------------------------------------------------------------------- 22 | | 23 | | Here you may configure the connection information for each server that 24 | | is used by your application. A default configuration has been added 25 | | for each back-end shipped with Laravel. You are free to add more. 26 | | 27 | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" 28 | | 29 | */ 30 | 31 | 'connections' => [ 32 | 33 | 'sync' => [ 34 | 'driver' => 'sync', 35 | ], 36 | 37 | 'database' => [ 38 | 'driver' => 'database', 39 | 'table' => 'jobs', 40 | 'queue' => 'default', 41 | 'retry_after' => 90, 42 | 'after_commit' => false, 43 | ], 44 | 45 | 'beanstalkd' => [ 46 | 'driver' => 'beanstalkd', 47 | 'host' => 'localhost', 48 | 'queue' => 'default', 49 | 'retry_after' => 90, 50 | 'block_for' => 0, 51 | 'after_commit' => false, 52 | ], 53 | 54 | 'sqs' => [ 55 | 'driver' => 'sqs', 56 | 'key' => env('AWS_ACCESS_KEY_ID'), 57 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 58 | 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), 59 | 'queue' => env('SQS_QUEUE', 'default'), 60 | 'suffix' => env('SQS_SUFFIX'), 61 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 62 | 'after_commit' => false, 63 | ], 64 | 65 | 'redis' => [ 66 | 'driver' => 'redis', 67 | 'connection' => 'default', 68 | 'queue' => env('REDIS_QUEUE', 'default'), 69 | 'retry_after' => 90, 70 | 'block_for' => null, 71 | 'after_commit' => false, 72 | ], 73 | 74 | ], 75 | 76 | /* 77 | |-------------------------------------------------------------------------- 78 | | Failed Queue Jobs 79 | |-------------------------------------------------------------------------- 80 | | 81 | | These options configure the behavior of failed queue job logging so you 82 | | can control which database and table are used to store the jobs that 83 | | have failed. You may change them to any database / table you wish. 84 | | 85 | */ 86 | 87 | 'failed' => [ 88 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 89 | 'database' => env('DB_CONNECTION', 'mysql'), 90 | 'table' => 'failed_jobs', 91 | ], 92 | 93 | ]; 94 | -------------------------------------------------------------------------------- /config/sanctum.php: -------------------------------------------------------------------------------- 1 | explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( 19 | '%s%s', 20 | 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', 21 | Sanctum::currentApplicationUrlWithPort() 22 | ))), 23 | 24 | /* 25 | |-------------------------------------------------------------------------- 26 | | Sanctum Guards 27 | |-------------------------------------------------------------------------- 28 | | 29 | | This array contains the authentication guards that will be checked when 30 | | Sanctum is trying to authenticate a request. If none of these guards 31 | | are able to authenticate the request, Sanctum will use the bearer 32 | | token that's present on an incoming request for authentication. 33 | | 34 | */ 35 | 36 | 'guard' => ['web'], 37 | 38 | /* 39 | |-------------------------------------------------------------------------- 40 | | Expiration Minutes 41 | |-------------------------------------------------------------------------- 42 | | 43 | | This value controls the number of minutes until an issued token will be 44 | | considered expired. If this value is null, personal access tokens do 45 | | not expire. This won't tweak the lifetime of first-party sessions. 46 | | 47 | */ 48 | 49 | 'expiration' => null, 50 | 51 | /* 52 | |-------------------------------------------------------------------------- 53 | | Sanctum Middleware 54 | |-------------------------------------------------------------------------- 55 | | 56 | | When authenticating your first-party SPA with Sanctum you may need to 57 | | customize some of the middleware Sanctum uses while processing the 58 | | request. You may change the middleware listed below as required. 59 | | 60 | */ 61 | 62 | 'middleware' => [ 63 | 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class, 64 | 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class, 65 | ], 66 | 67 | ]; 68 | -------------------------------------------------------------------------------- /config/services.php: -------------------------------------------------------------------------------- 1 | [ 18 | 'domain' => env('MAILGUN_DOMAIN'), 19 | 'secret' => env('MAILGUN_SECRET'), 20 | 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), 21 | 'scheme' => 'https', 22 | ], 23 | 24 | 'postmark' => [ 25 | 'token' => env('POSTMARK_TOKEN'), 26 | ], 27 | 28 | 'ses' => [ 29 | 'key' => env('AWS_ACCESS_KEY_ID'), 30 | 'secret' => env('AWS_SECRET_ACCESS_KEY'), 31 | 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 32 | ], 33 | 34 | ]; 35 | -------------------------------------------------------------------------------- /config/view.php: -------------------------------------------------------------------------------- 1 | [ 17 | resource_path('views'), 18 | ], 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Compiled View Path 23 | |-------------------------------------------------------------------------- 24 | | 25 | | This option determines where all the compiled Blade templates will be 26 | | stored for your application. Typically, this is within the storage 27 | | directory. However, as usual, you are free to change this value. 28 | | 29 | */ 30 | 31 | 'compiled' => env( 32 | 'VIEW_COMPILED_PATH', 33 | realpath(storage_path('framework/views')) 34 | ), 35 | 36 | ]; 37 | -------------------------------------------------------------------------------- /database/.gitignore: -------------------------------------------------------------------------------- 1 | *.sqlite* 2 | -------------------------------------------------------------------------------- /database/factories/ArticleFactory.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | class ArticleFactory extends Factory 13 | { 14 | /** 15 | * Define the model's default state. 16 | * 17 | * @return array 18 | */ 19 | public function definition() 20 | { 21 | return [ 22 | 'author_id' => User::factory(), 23 | 'slug' => fn (array $attrs) => Str::slug($attrs['title']), 24 | 'title' => $this->faker->unique()->sentence(4), 25 | 'description' => $this->faker->paragraph(), 26 | 'body' => $this->faker->text(), 27 | 'created_at' => function (array $attributes) { 28 | $user = User::find($attributes['author_id']); 29 | 30 | return $this->faker->dateTimeBetween($user->created_at); 31 | }, 32 | 'updated_at' => function (array $attributes) { 33 | $createdAt = $attributes['created_at']; 34 | 35 | return $this->faker->optional(25, $createdAt) 36 | ->dateTimeBetween($createdAt); 37 | }, 38 | ]; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /database/factories/CommentFactory.php: -------------------------------------------------------------------------------- 1 | 11 | */ 12 | class CommentFactory extends Factory 13 | { 14 | /** 15 | * Define the model's default state. 16 | * 17 | * @return array 18 | */ 19 | public function definition() 20 | { 21 | return [ 22 | 'article_id' => Article::factory(), 23 | 'author_id' => User::factory(), 24 | 'body' => $this->faker->sentence(), 25 | 'created_at' => function (array $attributes) { 26 | $article = Article::find($attributes['article_id']); 27 | 28 | return $this->faker->dateTimeBetween($article->created_at); 29 | }, 30 | 'updated_at' => function (array $attributes) { 31 | return $attributes['created_at']; 32 | }, 33 | ]; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /database/factories/TagFactory.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | class TagFactory extends Factory 11 | { 12 | /** 13 | * Define the model's default state. 14 | * 15 | * @return array 16 | */ 17 | public function definition() 18 | { 19 | $createdAt = $this->faker->dateTimeThisDecade(); 20 | 21 | return [ 22 | 'name' => $this->faker->unique()->word(), 23 | 'created_at' => $createdAt, 24 | 'updated_at' => $createdAt, 25 | ]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /database/factories/UserFactory.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | class UserFactory extends Factory 11 | { 12 | /** 13 | * Define the model's default state. 14 | * 15 | * @return array 16 | */ 17 | public function definition() 18 | { 19 | return [ 20 | 'username' => $this->faker->unique()->userName(), 21 | 'email' => $this->faker->unique()->safeEmail(), 22 | 'bio' => $this->faker->optional()->paragraph(), 23 | 'image' => $this->faker->optional()->imageUrl(), 24 | 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 25 | 'created_at' => $createdAt = $this->faker->dateTimeThisDecade(), 26 | 'updated_at' => $this->faker->optional(50, $createdAt) 27 | ->dateTimeBetween($createdAt), 28 | ]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /database/migrations/2014_10_12_000000_create_users_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | $table->string('name')->nullable(); 19 | $table->string('email')->unique(); 20 | $table->timestamp('email_verified_at')->nullable(); 21 | $table->string('password'); 22 | $table->rememberToken(); 23 | $table->timestamps(); 24 | }); 25 | } 26 | 27 | /** 28 | * Reverse the migrations. 29 | * 30 | * @return void 31 | */ 32 | public function down() 33 | { 34 | Schema::dropIfExists('users'); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /database/migrations/2014_10_12_100000_create_password_resets_table.php: -------------------------------------------------------------------------------- 1 | string('email')->index(); 18 | $table->string('token'); 19 | $table->timestamp('created_at')->nullable(); 20 | }); 21 | } 22 | 23 | /** 24 | * Reverse the migrations. 25 | * 26 | * @return void 27 | */ 28 | public function down() 29 | { 30 | Schema::dropIfExists('password_resets'); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /database/migrations/2019_08_19_000000_create_failed_jobs_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | $table->string('uuid')->unique(); 19 | $table->text('connection'); 20 | $table->text('queue'); 21 | $table->longText('payload'); 22 | $table->longText('exception'); 23 | $table->timestamp('failed_at')->useCurrent(); 24 | }); 25 | } 26 | 27 | /** 28 | * Reverse the migrations. 29 | * 30 | * @return void 31 | */ 32 | public function down() 33 | { 34 | Schema::dropIfExists('failed_jobs'); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | $table->morphs('tokenable'); 19 | $table->string('name'); 20 | $table->string('token', 64)->unique(); 21 | $table->text('abilities')->nullable(); 22 | $table->timestamp('last_used_at')->nullable(); 23 | $table->timestamps(); 24 | }); 25 | } 26 | 27 | /** 28 | * Reverse the migrations. 29 | * 30 | * @return void 31 | */ 32 | public function down() 33 | { 34 | Schema::dropIfExists('personal_access_tokens'); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /database/migrations/2021_05_21_130644_add_fields_to_users_table.php: -------------------------------------------------------------------------------- 1 | string('username')->unique(); 18 | $table->text('bio')->nullable(); 19 | $table->text('image')->nullable(); 20 | }); 21 | } 22 | 23 | /** 24 | * Reverse the migrations. 25 | * 26 | * @return void 27 | */ 28 | public function down() 29 | { 30 | Schema::table('users', function (Blueprint $table) { 31 | $table->dropColumn(['username', 'bio', 'image']); 32 | }); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /database/migrations/2021_05_23_123208_create_user_follower_table.php: -------------------------------------------------------------------------------- 1 | foreignId('author_id')->constrained('users')->onDelete('cascade'); 18 | $table->foreignId('follower_id')->constrained('users')->onDelete('cascade'); 19 | 20 | $table->unique(['author_id', 'follower_id']); 21 | }); 22 | } 23 | 24 | /** 25 | * Reverse the migrations. 26 | * 27 | * @return void 28 | */ 29 | public function down() 30 | { 31 | Schema::dropIfExists('author_follower'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /database/migrations/2021_05_23_150828_create_articles_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | 19 | $table->foreignId('author_id')->constrained('users')->onDelete('cascade'); 20 | $table->string('slug')->unique(); 21 | 22 | $table->string('title'); 23 | $table->string('description', 510); 24 | $table->text('body'); 25 | 26 | $table->timestamps(); 27 | }); 28 | } 29 | 30 | /** 31 | * Reverse the migrations. 32 | * 33 | * @return void 34 | */ 35 | public function down() 36 | { 37 | Schema::dropIfExists('articles'); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /database/migrations/2021_05_23_150839_create_comments_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | 19 | $table->foreignId('article_id')->constrained('articles')->onDelete('cascade'); 20 | $table->foreignId('author_id')->constrained('users')->onDelete('cascade'); 21 | $table->text('body'); 22 | 23 | $table->timestamps(); 24 | }); 25 | } 26 | 27 | /** 28 | * Reverse the migrations. 29 | * 30 | * @return void 31 | */ 32 | public function down() 33 | { 34 | Schema::dropIfExists('comments'); 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /database/migrations/2021_05_23_150848_create_tags_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | 19 | $table->string('name')->unique(); 20 | 21 | $table->timestamps(); 22 | }); 23 | } 24 | 25 | /** 26 | * Reverse the migrations. 27 | * 28 | * @return void 29 | */ 30 | public function down() 31 | { 32 | Schema::dropIfExists('tags'); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /database/migrations/2021_05_23_151511_create_article_tag_table.php: -------------------------------------------------------------------------------- 1 | foreignId('article_id')->constrained('articles')->onDelete('cascade'); 18 | $table->foreignId('tag_id')->constrained('tags')->onDelete('cascade'); 19 | 20 | $table->unique(['article_id', 'tag_id']); 21 | }); 22 | } 23 | 24 | /** 25 | * Reverse the migrations. 26 | * 27 | * @return void 28 | */ 29 | public function down() 30 | { 31 | Schema::dropIfExists('article_tag'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /database/migrations/2021_05_23_152011_create_article_favorite_table.php: -------------------------------------------------------------------------------- 1 | foreignId('article_id')->constrained('articles')->onDelete('cascade'); 18 | $table->foreignId('user_id')->constrained('users')->onDelete('cascade'); 19 | 20 | $table->unique(['article_id', 'user_id']); 21 | }); 22 | } 23 | 24 | /** 25 | * Reverse the migrations. 26 | * 27 | * @return void 28 | */ 29 | public function down() 30 | { 31 | Schema::dropIfExists('article_favorite'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /database/seeders/DatabaseSeeder.php: -------------------------------------------------------------------------------- 1 | |\Illuminate\Database\Eloquent\Collection $users */ 22 | $users = User::factory()->count(20)->create(); 23 | 24 | foreach ($users as $user) { 25 | $user->followers()->attach($users->random(rand(0, 5))); 26 | } 27 | 28 | /** @var array
|\Illuminate\Database\Eloquent\Collection
$articles */ 29 | $articles = Article::factory() 30 | ->count(30) 31 | ->state(new Sequence(fn() => [ 32 | 'author_id' => $users->random(), 33 | ])) 34 | ->create(); 35 | 36 | /** @var array|\Illuminate\Database\Eloquent\Collection $tags */ 37 | $tags = Tag::factory()->count(20)->create(); 38 | 39 | foreach ($articles as $article) { 40 | $article->tags()->attach($tags->random(rand(0, 6))); 41 | $article->favoredUsers()->attach($users->random(rand(0, 8))); 42 | } 43 | 44 | Comment::factory() 45 | ->count(60) 46 | ->state(new Sequence(fn() => [ 47 | 'article_id' => $articles->random(), 48 | 'author_id' => $users->random(), 49 | ])) 50 | ->create(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # For more information: https://laravel.com/docs/sail 2 | version: '3.9' 3 | 4 | services: 5 | laravel.test: 6 | build: 7 | context: ./vendor/laravel/sail/runtimes/8.1 8 | dockerfile: Dockerfile 9 | args: 10 | WWWGROUP: '${WWWGROUP}' 11 | image: sail-8.1/app 12 | extra_hosts: 13 | - 'host.docker.internal:host-gateway' 14 | ports: 15 | - '${APP_PORT:-80}:80' 16 | - '${HMR_PORT:-8080}:8080' 17 | environment: 18 | PHP_IDE_CONFIG: 'serverName=laravel-realworld.test' 19 | WWWUSER: '${WWWUSER}' 20 | LARAVEL_SAIL: 1 21 | XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}' 22 | XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}' 23 | volumes: 24 | - '.:/var/www/html' 25 | networks: 26 | - sail 27 | depends_on: 28 | - pgsql 29 | 30 | pgsql: 31 | image: 'postgres:14-alpine' 32 | ports: 33 | - '${FORWARD_DB_PORT:-5432}:5432' 34 | environment: 35 | PGPASSWORD: '${DB_PASSWORD:-secret}' 36 | POSTGRES_DB: '${DB_DATABASE}' 37 | POSTGRES_USER: '${DB_USERNAME}' 38 | POSTGRES_PASSWORD: '${DB_PASSWORD:-secret}' 39 | volumes: 40 | - 'sail-pgsql:/var/lib/postgresql/data' 41 | - './vendor/laravel/sail/database/pgsql/create-testing-database.sql:/docker-entrypoint-initdb.d/10-create-testing-database.sql' 42 | networks: 43 | - sail 44 | healthcheck: 45 | test: [ "CMD", "pg_isready", "-q", "-d", "${DB_DATABASE}", "-U", "${DB_USERNAME}" ] 46 | retries: 3 47 | timeout: 5s 48 | 49 | networks: 50 | sail: 51 | name: laravel-realworld-network 52 | driver: bridge 53 | 54 | volumes: 55 | sail-pgsql: 56 | name: laravel-realworld-database 57 | driver: local 58 | -------------------------------------------------------------------------------- /lang/en/auth.php: -------------------------------------------------------------------------------- 1 | 'These credentials do not match our records.', 17 | 'password' => 'The provided password is incorrect.', 18 | 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', 19 | 20 | ]; 21 | -------------------------------------------------------------------------------- /lang/en/models.php: -------------------------------------------------------------------------------- 1 | [ 15 | '404' => 'Resource not found.', 16 | ], 17 | 18 | 'article' => [ 19 | 'deleted' => 'Article deleted.', 20 | ], 21 | 22 | 'comment' => [ 23 | 'deleted' => 'Comment deleted.', 24 | ], 25 | 26 | ]; 27 | -------------------------------------------------------------------------------- /lang/en/pagination.php: -------------------------------------------------------------------------------- 1 | '« Previous', 17 | 'next' => 'Next »', 18 | 19 | ]; 20 | -------------------------------------------------------------------------------- /lang/en/passwords.php: -------------------------------------------------------------------------------- 1 | 'Your password has been reset!', 17 | 'sent' => 'We have emailed your password reset link!', 18 | 'throttled' => 'Please wait before retrying.', 19 | 'token' => 'This password reset token is invalid.', 20 | 'user' => "We can't find a user with that email address.", 21 | 22 | ]; 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "dev": "npm run development", 5 | "development": "mix", 6 | "watch": "mix watch", 7 | "watch-poll": "mix watch -- --watch-options-poll=1000", 8 | "hot": "mix watch --hot", 9 | "prod": "npm run production", 10 | "production": "mix --production" 11 | }, 12 | "devDependencies": { 13 | "axios": "^0.25", 14 | "laravel-mix": "^6.0.6", 15 | "lodash": "^4.17.19", 16 | "postcss": "^8.1.14" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /phpstan-baseline.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | ignoreErrors: 3 | - 4 | message: "#^Parameter \\#1 \\$user of method Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\:\\:followedAuthorsOf\\(\\) expects App\\\\Models\\\\User, App\\\\Models\\\\User\\|null given\\.$#" 5 | count: 1 6 | path: app/Http/Controllers/Api/Articles/ArticleController.php 7 | 8 | - 9 | message: "#^Unable to resolve the template type TKey in call to function collect$#" 10 | count: 2 11 | path: app/Http/Controllers/Api/Articles/ArticleController.php 12 | 13 | - 14 | message: "#^Unable to resolve the template type TValue in call to function collect$#" 15 | count: 2 16 | path: app/Http/Controllers/Api/Articles/ArticleController.php 17 | 18 | - 19 | message: "#^Parameter \\#1 \\$ids of method Illuminate\\\\Database\\\\Eloquent\\\\Relations\\\\BelongsToMany\\\\:\\:syncWithoutDetaching\\(\\) expects array\\|Illuminate\\\\Database\\\\Eloquent\\\\Model\\|Illuminate\\\\Support\\\\Collection, App\\\\Models\\\\User\\|null given\\.$#" 20 | count: 1 21 | path: app/Http/Controllers/Api/ProfileController.php 22 | 23 | - 24 | message: "#^Parameter \\#1 \\$user of method App\\\\Models\\\\Article\\:\\:favoredBy\\(\\) expects App\\\\Models\\\\User, App\\\\Models\\\\User\\|null given\\.$#" 25 | count: 1 26 | path: app/Http/Resources/Api/ArticleResource.php 27 | 28 | - 29 | message: "#^Cannot call method following\\(\\) on App\\\\Models\\\\User\\|null\\.$#" 30 | count: 1 31 | path: app/Http/Resources/Api/ProfileResource.php 32 | 33 | - 34 | message: "#^Parameter \\#1 \\$key of method Illuminate\\\\Cache\\\\RateLimiting\\\\Limit\\:\\:by\\(\\) expects string, int\\\\|int\\<1, max\\>\\|string\\|null given\\.$#" 35 | count: 1 36 | path: app/Providers/RouteServiceProvider.php 37 | 38 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | includes: 2 | - phpstan-baseline.neon 3 | 4 | parameters: 5 | level: 8 6 | paths: 7 | - app 8 | - tests 9 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | ./tests/Unit 11 | 12 | 13 | ./tests/Feature 14 | 15 | 16 | 17 | 18 | ./app 19 | 20 | 21 | ./app/Providers 22 | ./app/Http/Middleware 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /public/.htaccess: -------------------------------------------------------------------------------- 1 | 2 | 3 | Options -MultiViews -Indexes 4 | 5 | 6 | RewriteEngine On 7 | 8 | # Handle Authorization Header 9 | RewriteCond %{HTTP:Authorization} . 10 | RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 11 | 12 | # Redirect Trailing Slashes If Not A Folder... 13 | RewriteCond %{REQUEST_FILENAME} !-d 14 | RewriteCond %{REQUEST_URI} (.+)/$ 15 | RewriteRule ^ %1 [L,R=301] 16 | 17 | # Send Requests To Front Controller... 18 | RewriteCond %{REQUEST_FILENAME} !-d 19 | RewriteCond %{REQUEST_FILENAME} !-f 20 | RewriteRule ^ index.php [L] 21 | 22 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/f1amy/laravel-realworld-example-app/c14fb8370b71a42a3a74b8ea936a1f96b2af9d69/public/favicon.ico -------------------------------------------------------------------------------- /public/index.php: -------------------------------------------------------------------------------- 1 | make(Kernel::class); 50 | 51 | $response = $kernel->handle( 52 | $request = Request::capture() 53 | )->send(); 54 | 55 | $kernel->terminate($request, $response); 56 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: 3 | -------------------------------------------------------------------------------- /resources/css/app.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/f1amy/laravel-realworld-example-app/c14fb8370b71a42a3a74b8ea936a1f96b2af9d69/resources/css/app.css -------------------------------------------------------------------------------- /resources/js/app.js: -------------------------------------------------------------------------------- 1 | import './bootstrap'; 2 | -------------------------------------------------------------------------------- /resources/js/bootstrap.js: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | window._ = _; 3 | 4 | /** 5 | * We'll load the axios HTTP library which allows us to easily issue requests 6 | * to our Laravel back-end. This library automatically handles sending the 7 | * CSRF token as a header based on the value of the "XSRF" token cookie. 8 | */ 9 | 10 | import axios from 'axios'; 11 | window.axios = axios; 12 | 13 | window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; 14 | 15 | /** 16 | * Echo exposes an expressive API for subscribing to channels and listening 17 | * for events that are broadcast by Laravel. Echo and event broadcasting 18 | * allows your team to easily build robust real-time web applications. 19 | */ 20 | 21 | // import Echo from 'laravel-echo'; 22 | 23 | // import Pusher from 'pusher-js'; 24 | // window.Pusher = Pusher; 25 | 26 | // window.Echo = new Echo({ 27 | // broadcaster: 'pusher', 28 | // key: process.env.MIX_PUSHER_APP_KEY, 29 | // cluster: process.env.MIX_PUSHER_APP_CLUSTER, 30 | // forceTLS: true 31 | // }); 32 | -------------------------------------------------------------------------------- /resources/views/vendor/l5-swagger/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/f1amy/laravel-realworld-example-app/c14fb8370b71a42a3a74b8ea936a1f96b2af9d69/resources/views/vendor/l5-swagger/.gitkeep -------------------------------------------------------------------------------- /resources/views/vendor/l5-swagger/index.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {{config('l5-swagger.documentations.'.$documentation.'.api.title')}} 7 | 8 | 9 | 10 | 11 | 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 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /routes/api.php: -------------------------------------------------------------------------------- 1 | group(function () { 24 | Route::name('users.')->group(function () { 25 | Route::middleware('auth:api')->group(function () { 26 | Route::get('user', [UserController::class, 'show'])->name('current'); 27 | Route::put('user', [UserController::class, 'update'])->name('update'); 28 | }); 29 | 30 | Route::post('users/login', [AuthController::class, 'login'])->name('login'); 31 | Route::post('users', [AuthController::class, 'register'])->name('register'); 32 | }); 33 | 34 | Route::name('profiles.')->group(function () { 35 | Route::middleware('auth:api')->group(function () { 36 | Route::post('profiles/{username}/follow', [ProfileController::class, 'follow'])->name('follow'); 37 | Route::delete('profiles/{username}/follow', [ProfileController::class, 'unfollow'])->name('unfollow'); 38 | }); 39 | 40 | Route::get('profiles/{username}', [ProfileController::class, 'show'])->name('get'); 41 | }); 42 | 43 | Route::name('articles.')->group(function () { 44 | Route::middleware('auth:api')->group(function () { 45 | Route::get('articles/feed', [ArticleController::class, 'feed'])->name('feed'); 46 | Route::post('articles', [ArticleController::class, 'create'])->name('create'); 47 | Route::put('articles/{slug}', [ArticleController::class, 'update'])->name('update'); 48 | Route::delete('articles/{slug}', [ArticleController::class, 'delete'])->name('delete'); 49 | }); 50 | 51 | Route::get('articles', [ArticleController::class, 'list'])->name('list'); 52 | Route::get('articles/{slug}', [ArticleController::class, 'show'])->name('get'); 53 | 54 | Route::name('comments.')->group(function () { 55 | Route::middleware('auth:api')->group(function () { 56 | Route::post('articles/{slug}/comments', [CommentsController::class, 'create'])->name('create'); 57 | Route::delete('articles/{slug}/comments/{id}', [CommentsController::class, 'delete'])->name('delete'); 58 | }); 59 | 60 | Route::get('articles/{slug}/comments', [CommentsController::class, 'list'])->name('get'); 61 | }); 62 | 63 | Route::name('favorites.')->group(function () { 64 | Route::middleware('auth:api')->group(function () { 65 | Route::post('articles/{slug}/favorite', [FavoritesController::class, 'add'])->name('add'); 66 | Route::delete('articles/{slug}/favorite', [FavoritesController::class, 'remove'])->name('remove'); 67 | }); 68 | }); 69 | }); 70 | 71 | Route::name('tags.')->group(function () { 72 | Route::get('tags', [TagsController::class, 'list'])->name('list'); 73 | }); 74 | }); 75 | -------------------------------------------------------------------------------- /routes/channels.php: -------------------------------------------------------------------------------- 1 | id === (int) $id; 18 | }); 19 | -------------------------------------------------------------------------------- /routes/console.php: -------------------------------------------------------------------------------- 1 | comment(Inspiring::quote()); 19 | })->purpose('Display an inspiring quote'); 20 | -------------------------------------------------------------------------------- /routes/web.php: -------------------------------------------------------------------------------- 1 | make(Kernel::class)->bootstrap(); 19 | 20 | return $app; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tests/Feature/Api/Article/ArticleFeedTest.php: -------------------------------------------------------------------------------- 1 | has(Article::factory()->count(6), 'articles') 22 | ->count(5); 23 | 24 | /** @var User $user */ 25 | $user = User::factory() 26 | ->has($authors, 'authors') 27 | ->create(); 28 | 29 | $this->user = $user; 30 | } 31 | 32 | public function testArticleFeed(): void 33 | { 34 | // new dummy articles shouldn't be returned 35 | Article::factory()->count(5)->create(); 36 | 37 | $response = $this->actingAs($this->user) 38 | ->getJson('/api/articles/feed'); 39 | 40 | $response->assertOk() 41 | ->assertJson(fn (AssertableJson $json) => 42 | $json->where('articlesCount', 20) 43 | ->count('articles', 20) 44 | ->has('articles', fn (AssertableJson $items) => 45 | $items->each(fn (AssertableJson $item) => 46 | $item->where('tagList', []) 47 | ->whereAllType([ 48 | 'slug' => 'string', 49 | 'title' => 'string', 50 | 'description' => 'string', 51 | 'body' => 'string', 52 | 'createdAt' => 'string', 53 | 'updatedAt' => 'string', 54 | ]) 55 | ->whereAll([ 56 | 'favorited' => false, 57 | 'favoritesCount' => 0, 58 | ]) 59 | ->has('author', fn (AssertableJson $subItem) => 60 | $subItem->where('following', true) 61 | ->whereAllType([ 62 | 'username' => 'string', 63 | 'bio' => 'string|null', 64 | 'image' => 'string|null', 65 | ]) 66 | ) 67 | ) 68 | ) 69 | ); 70 | 71 | // verify all authors are followed 72 | foreach ($response['articles'] as $article) { 73 | $this->assertTrue( 74 | Arr::get($article, 'author.following'), 75 | 'Author of the article must be followed.' 76 | ); 77 | } 78 | } 79 | 80 | public function testArticleFeedLimit(): void 81 | { 82 | $response = $this->actingAs($this->user) 83 | ->getJson('/api/articles/feed?limit=25'); 84 | 85 | $response->assertOk() 86 | ->assertJsonPath('articlesCount', 25) 87 | ->assertJsonCount(25, 'articles'); 88 | } 89 | 90 | public function testArticleFeedOffset(): void 91 | { 92 | $response = $this->actingAs($this->user) 93 | ->getJson('/api/articles/feed?offset=20'); 94 | 95 | $response->assertOk() 96 | ->assertJsonPath('articlesCount', 10) 97 | ->assertJsonCount(10, 'articles'); 98 | } 99 | 100 | /** 101 | * @dataProvider queryProvider 102 | * @param array $data 103 | * @param string|array $errors 104 | */ 105 | public function testArticleFeedValidation(array $data, $errors): void 106 | { 107 | $response = $this->actingAs($this->user) 108 | ->json('GET', '/api/articles/feed', $data); 109 | 110 | $response->assertUnprocessable() 111 | ->assertInvalid($errors); 112 | } 113 | 114 | public function testArticleFeedWithoutAuth(): void 115 | { 116 | $this->getJson('/api/articles/feed') 117 | ->assertUnauthorized(); 118 | } 119 | 120 | /** 121 | * @return array> 122 | */ 123 | public function queryProvider(): array 124 | { 125 | $errors = ['limit', 'offset']; 126 | 127 | return [ 128 | 'not integer' => [['limit' => 'string', 'offset' => 0.123], $errors], 129 | 'less than zero' => [['limit' => -123, 'offset' => -321], $errors], 130 | ]; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /tests/Feature/Api/Article/DeleteArticleTest.php: -------------------------------------------------------------------------------- 1 | create(); 20 | /** @var User $user */ 21 | $user = User::factory()->create(); 22 | 23 | $this->article = $article; 24 | $this->user = $user; 25 | } 26 | 27 | public function testDeleteArticle(): void 28 | { 29 | $this->actingAs($this->article->author) 30 | ->deleteJson("/api/articles/{$this->article->slug}") 31 | ->assertOk(); 32 | 33 | $this->assertModelMissing($this->article); 34 | } 35 | 36 | public function testDeleteForeignArticle(): void 37 | { 38 | $this->actingAs($this->user) 39 | ->deleteJson("/api/articles/{$this->article->slug}") 40 | ->assertForbidden(); 41 | 42 | $this->assertModelExists($this->article); 43 | } 44 | 45 | public function testDeleteNonExistentArticle(): void 46 | { 47 | $this->actingAs($this->user) 48 | ->deleteJson("/api/articles/non-existent") 49 | ->assertNotFound(); 50 | } 51 | 52 | public function testDeleteArticleWithoutAuth(): void 53 | { 54 | $this->deleteJson("/api/articles/{$this->article->slug}") 55 | ->assertUnauthorized(); 56 | 57 | $this->assertModelExists($this->article); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /tests/Feature/Api/Article/ShowArticleTest.php: -------------------------------------------------------------------------------- 1 | has(Tag::factory()->count(5), 'tags') 18 | ->create(); 19 | $author = $article->author; 20 | $tags = $article->tags; 21 | 22 | $response = $this->getJson("/api/articles/{$article->slug}"); 23 | 24 | $response->assertOk() 25 | ->assertJson(fn (AssertableJson $json) => 26 | $json->has('article', fn (AssertableJson $item) => 27 | $item->missing('favorited') 28 | ->whereAll([ 29 | 'slug' => $article->slug, 30 | 'title' => $article->title, 31 | 'description' => $article->description, 32 | 'body' => $article->body, 33 | 'tagList' => $tags->pluck('name'), 34 | 'createdAt' => $article->created_at?->toISOString(), 35 | 'updatedAt' => $article->updated_at?->toISOString(), 36 | 'favoritesCount' => 0, 37 | ]) 38 | ->has('author', fn (AssertableJson $subItem) => 39 | $subItem->missing('following') 40 | ->whereAll([ 41 | 'username' => $author->username, 42 | 'bio' => $author->bio, 43 | 'image' => $author->image, 44 | ]) 45 | ) 46 | ) 47 | ); 48 | } 49 | 50 | public function testShowFavoredArticleWithUnfollowedAuthor(): void 51 | { 52 | /** @var User $user */ 53 | $user = User::factory()->create(); 54 | /** @var Article $article */ 55 | $article = Article::factory() 56 | ->hasAttached($user, [], 'favoredUsers') 57 | ->create(); 58 | 59 | $this->assertTrue($article->favoredUsers->contains($user)); 60 | 61 | $response = $this->actingAs($user) 62 | ->getJson("/api/articles/{$article->slug}"); 63 | 64 | $response->assertOk() 65 | ->assertJsonPath('article.favorited', true) 66 | ->assertJsonPath('article.favoritesCount', 1) 67 | ->assertJsonPath('article.author.following', false); 68 | } 69 | 70 | public function testShowUnfavoredArticleWithFollowedAuthor(): void 71 | { 72 | /** @var User $user */ 73 | $user = User::factory()->create(); 74 | /** @var User $author */ 75 | $author = User::factory() 76 | ->hasAttached($user, [], 'followers') 77 | ->create(); 78 | /** @var Article $article */ 79 | $article = Article::factory() 80 | ->for($author, 'author') 81 | ->create(); 82 | 83 | $this->assertTrue($author->followers->contains($user)); 84 | 85 | $response = $this->actingAs($user) 86 | ->getJson("/api/articles/{$article->slug}"); 87 | 88 | $response->assertOk() 89 | ->assertJsonPath('article.favorited', false) 90 | ->assertJsonPath('article.favoritesCount', 0) 91 | ->assertJsonPath('article.author.following', true); 92 | } 93 | 94 | public function testShowNonExistentArticle(): void 95 | { 96 | $this->getJson('/api/articles/non-existent') 97 | ->assertNotFound(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /tests/Feature/Api/Auth/JwtGuardTest.php: -------------------------------------------------------------------------------- 1 | create(); 20 | 21 | $this->user = $user; 22 | $this->token = Jwt\Generator::token($user); 23 | } 24 | 25 | public function testGuardTokenParse(): void 26 | { 27 | $this->getJson('/api/user?token=string') 28 | ->assertUnauthorized(); 29 | } 30 | 31 | public function testGuardTokenValidation(): void 32 | { 33 | $this->user->delete(); 34 | 35 | $this->getJson("/api/user?token={$this->token}") 36 | ->assertUnauthorized(); 37 | } 38 | 39 | public function testGuardWithHeaderToken(): void 40 | { 41 | $response = $this->getJson('/api/user', [ 42 | 'Authorization' => "Token {$this->token}", 43 | ]); 44 | 45 | $response->assertOk(); 46 | } 47 | 48 | public function testGuardWithQueryToken(): void 49 | { 50 | $this->getJson("/api/user?token={$this->token}") 51 | ->assertOk(); 52 | } 53 | 54 | public function testGuardWithJsonBodyToken(): void 55 | { 56 | $response = $this->json('GET', '/api/user', [ 57 | 'token' => $this->token, 58 | ]); 59 | 60 | $response->assertOk(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/Feature/Api/Auth/LoginTest.php: -------------------------------------------------------------------------------- 1 | faker->password(8); 19 | /** @var User $user */ 20 | $user = User::factory() 21 | ->state(['password' => Hash::make($password)]) 22 | ->create(); 23 | 24 | $response = $this->postJson('/api/users/login', [ 25 | 'user' => [ 26 | 'email' => $user->email, 27 | 'password' => $password, 28 | ], 29 | ]); 30 | 31 | $response->assertOk() 32 | ->assertJson(fn (AssertableJson $json) => 33 | $json->has('user', fn (AssertableJson $item) => 34 | $item->whereType('token', 'string') 35 | ->whereAll([ 36 | 'username' => $user->username, 37 | 'email' => $user->email, 38 | 'bio' => $user->bio, 39 | 'image' => $user->image, 40 | ]) 41 | ) 42 | ); 43 | 44 | $token = Jwt\Parser::parse($response['user']['token']); 45 | $this->assertTrue(Jwt\Validator::validate($token)); 46 | } 47 | 48 | public function testLoginUserFail(): void 49 | { 50 | $password = 'knownPassword'; 51 | /** @var User $user */ 52 | $user = User::factory() 53 | ->state(['password' => Hash::make($password)]) 54 | ->create(); 55 | 56 | $response = $this->postJson('/api/users/login', [ 57 | 'user' => [ 58 | 'email' => $user->email, 59 | 'password' => 'differentPassword', 60 | ], 61 | ]); 62 | 63 | $response->assertUnprocessable() 64 | ->assertInvalid('user'); 65 | } 66 | 67 | /** 68 | * @dataProvider credentialsProvider 69 | * @param array $data 70 | * @param string|array $errors 71 | */ 72 | public function testLoginUserValidation(array $data, $errors): void 73 | { 74 | $response = $this->postJson('/api/users/login', $data); 75 | 76 | $response->assertUnprocessable() 77 | ->assertInvalid($errors); 78 | } 79 | 80 | /** 81 | * @return array> 82 | */ 83 | public function credentialsProvider(): array 84 | { 85 | $errors = ['email', 'password']; 86 | 87 | return [ 88 | 'required' => [[], $errors], 89 | 'not strings' => [[ 90 | 'user' => [ 91 | 'email' => [], 92 | 'password' => null, 93 | ], 94 | ], $errors], 95 | 'empty strings' => [[ 96 | 'user' => [ 97 | 'email' => '', 98 | 'password' => '', 99 | ], 100 | ], $errors], 101 | 'not email' => [['user' => ['email' => 'not an email']], 'email'], 102 | ]; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /tests/Feature/Api/Auth/RegisterTest.php: -------------------------------------------------------------------------------- 1 | faker->userName(); 18 | $email = $this->faker->safeEmail(); 19 | 20 | $response = $this->postJson('/api/users', [ 21 | 'user' => [ 22 | 'username' => $username, 23 | 'email' => $email, 24 | 'password' => $this->faker->password(8), 25 | ], 26 | ]); 27 | 28 | $response->assertCreated() 29 | ->assertJson(fn (AssertableJson $json) => 30 | $json->has('user', fn (AssertableJson $item) => 31 | $item->whereType('token', 'string') 32 | ->whereAll([ 33 | 'username' => $username, 34 | 'email' => $email, 35 | 'bio' => null, 36 | 'image' => null, 37 | ]) 38 | ) 39 | ); 40 | 41 | $token = Jwt\Parser::parse($response['user']['token']); 42 | $this->assertTrue(Jwt\Validator::validate($token)); 43 | } 44 | 45 | /** 46 | * @dataProvider userProvider 47 | * @param array $data 48 | * @param string|array $errors 49 | */ 50 | public function testRegisterUserValidation(array $data, $errors): void 51 | { 52 | $response = $this->postJson('/api/users', $data); 53 | 54 | $response->assertUnprocessable() 55 | ->assertInvalid($errors); 56 | } 57 | 58 | public function testRegisterUserValidationUnique(): void 59 | { 60 | /** @var User $user */ 61 | $user = User::factory()->create(); 62 | 63 | $response = $this->postJson('/api/users', [ 64 | 'user' => [ 65 | 'username' => $user->username, 66 | 'email' => $user->email, 67 | 'password' => $this->faker->password(8), 68 | ], 69 | ]); 70 | 71 | $response->assertUnprocessable() 72 | ->assertInvalid(['username', 'email']); 73 | } 74 | 75 | /** 76 | * @return array> 77 | */ 78 | public function userProvider(): array 79 | { 80 | $errors = ['username', 'email', 'password']; 81 | 82 | return [ 83 | 'required' => [[], $errors], 84 | 'not strings' => [[ 85 | 'user' => [ 86 | 'username' => 123, 87 | 'email' => [], 88 | 'password' => null, 89 | ], 90 | ], $errors], 91 | 'empty strings' => [[ 92 | 'user' => [ 93 | 'username' => '', 94 | 'email' => '', 95 | 'password' => '', 96 | ], 97 | ], $errors], 98 | 'bad username' => [['user' => ['username' => 'user n@me']], 'username'], 99 | 'not email' => [['user' => ['email' => 'not an email']], 'email'], 100 | 'small password' => [['user' => ['password' => 'small']], 'password'], 101 | ]; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /tests/Feature/Api/Comments/CreateCommentTest.php: -------------------------------------------------------------------------------- 1 | create(); 24 | /** @var User $user */ 25 | $user = User::factory()->create(); 26 | 27 | $this->article = $article; 28 | $this->user = $user; 29 | } 30 | 31 | public function testCreateCommentForArticle(): void 32 | { 33 | $message = $this->faker->sentence(); 34 | 35 | $response = $this->actingAs($this->user) 36 | ->postJson("/api/articles/{$this->article->slug}/comments", [ 37 | 'comment' => [ 38 | 'body' => $message, 39 | ], 40 | ]); 41 | 42 | $response->assertCreated() 43 | ->assertJson(fn (AssertableJson $json) => 44 | $json->has('comment', fn (AssertableJson $comment) => 45 | $comment->where('body', $message) 46 | ->whereAllType([ 47 | 'id' => 'integer', 48 | 'createdAt' => 'string', 49 | 'updatedAt' => 'string', 50 | ]) 51 | ->has('author', fn (AssertableJson $author) => 52 | $author->whereAll([ 53 | 'username' => $this->user->username, 54 | 'bio' => $this->user->bio, 55 | 'image' => $this->user->image, 56 | 'following' => false, 57 | ]) 58 | ) 59 | ) 60 | ); 61 | } 62 | 63 | /** 64 | * @dataProvider commentProvider 65 | * @param array $data 66 | */ 67 | public function testCreateCommentValidation(array $data): void 68 | { 69 | $response = $this->actingAs($this->user) 70 | ->postJson("/api/articles/{$this->article->slug}/comments", $data); 71 | 72 | $response->assertUnprocessable() 73 | ->assertInvalid('body'); 74 | } 75 | 76 | public function testCreateCommentForNonExistentArticle(): void 77 | { 78 | $response = $this->actingAs($this->user) 79 | ->postJson("/api/articles/non-existent/comments", [ 80 | 'comment' => [ 81 | 'body' => $this->faker->sentence(), 82 | ], 83 | ]); 84 | 85 | $response->assertNotFound(); 86 | } 87 | 88 | public function testCreateCommentWithoutAuth(): void 89 | { 90 | $response = $this->postJson("/api/articles/{$this->article->slug}/comments", [ 91 | 'comment' => [ 92 | 'body' => $this->faker->sentence(), 93 | ], 94 | ]); 95 | 96 | $response->assertUnauthorized(); 97 | } 98 | 99 | /** 100 | * @return array> 101 | */ 102 | public function commentProvider(): array 103 | { 104 | return [ 105 | 'empty data' => [[]], 106 | 'no comment wrap' => [['body' => 'example-message']], 107 | 'empty message' => [['comment' => ['body' => '']]], 108 | 'integer message' => [['comment' => ['body' => 123]]], 109 | 'array message' => [['comment' => ['body' => []]]], 110 | ]; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /tests/Feature/Api/Comments/DeleteCommentTest.php: -------------------------------------------------------------------------------- 1 | create(); 21 | 22 | $this->comment = $comment; 23 | $this->article = $comment->article; 24 | } 25 | 26 | public function testDeleteArticleComment(): void 27 | { 28 | $this->actingAs($this->comment->author) 29 | ->deleteJson("/api/articles/{$this->article->slug}/comments/{$this->comment->getKey()}") 30 | ->assertOk(); 31 | 32 | $this->assertModelMissing($this->comment); 33 | } 34 | 35 | public function testDeleteCommentOfNonExistentArticle(): void 36 | { 37 | $this->assertNotSame($nonExistentSlug = 'non-existent', $this->article->slug); 38 | 39 | $this->actingAs($this->comment->author) 40 | ->deleteJson("/api/articles/{$nonExistentSlug}/comments/{$this->comment->getKey()}") 41 | ->assertNotFound(); 42 | 43 | $this->assertModelExists($this->comment); 44 | } 45 | 46 | /** 47 | * @dataProvider nonExistentIdProvider 48 | * @param mixed $nonExistentId 49 | */ 50 | public function testDeleteNonExistentArticleComment($nonExistentId): void 51 | { 52 | $this->assertNotEquals($nonExistentId, $this->comment->getKey()); 53 | 54 | $this->actingAs($this->comment->author) 55 | ->deleteJson("/api/articles/{$this->article->slug}/comments/{$nonExistentId}") 56 | ->assertNotFound(); 57 | 58 | $this->assertModelExists($this->comment); 59 | } 60 | 61 | public function testDeleteForeignArticleComment(): void 62 | { 63 | /** @var User $user */ 64 | $user = User::factory()->create(); 65 | 66 | $this->actingAs($user) 67 | ->deleteJson("/api/articles/{$this->article->slug}/comments/{$this->comment->getKey()}") 68 | ->assertForbidden(); 69 | 70 | $this->assertModelExists($this->comment); 71 | } 72 | 73 | public function testDeleteCommentOfForeignArticle(): void 74 | { 75 | /** @var Article $article */ 76 | $article = Article::factory()->create(); 77 | 78 | $this->actingAs($this->comment->author) 79 | ->deleteJson("/api/articles/{$article->slug}/comments/{$this->comment->getKey()}") 80 | ->assertNotFound(); 81 | 82 | $this->assertModelExists($this->comment); 83 | } 84 | 85 | public function testDeleteCommentWithoutAuth(): void 86 | { 87 | $this->deleteJson("/api/articles/{$this->article->slug}/comments/{$this->comment->getKey()}") 88 | ->assertUnauthorized(); 89 | 90 | $this->assertModelExists($this->comment); 91 | } 92 | 93 | /** 94 | * @return array> 95 | */ 96 | public function nonExistentIdProvider(): array 97 | { 98 | return [ 99 | 'int key' => [123], 100 | 'string key' => ['non-existent'], 101 | ]; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /tests/Feature/Api/Comments/ListCommentsTest.php: -------------------------------------------------------------------------------- 1 | has(Comment::factory()->count(5), 'comments') 18 | ->create(); 19 | /** @var Comment $comment */ 20 | $comment = $article->comments->first(); 21 | $author = $comment->author; 22 | 23 | $response = $this->getJson("/api/articles/{$article->slug}/comments"); 24 | 25 | $response->assertOk() 26 | ->assertJson(fn (AssertableJson $json) => 27 | $json->has('comments', 5, fn (AssertableJson $item) => 28 | $item->where('id', $comment->getKey()) 29 | ->whereAll([ 30 | 'createdAt' => $comment->created_at?->toISOString(), 31 | 'updatedAt' => $comment->updated_at?->toISOString(), 32 | 'body' => $comment->body, 33 | ]) 34 | ->has('author', fn (AssertableJson $subItem) => 35 | $subItem->missing('following') 36 | ->whereAll([ 37 | 'username' => $author->username, 38 | 'bio' => $author->bio, 39 | 'image' => $author->image, 40 | ]) 41 | ) 42 | ) 43 | ); 44 | } 45 | 46 | public function testListArticleCommentsFollowedAuthor(): void 47 | { 48 | /** @var Comment $comment */ 49 | $comment = Comment::factory()->create(); 50 | $author = $comment->author; 51 | /** @var User $follower */ 52 | $follower = User::factory() 53 | ->hasAttached($author, [], 'authors') 54 | ->create(); 55 | $article = $comment->article; 56 | 57 | $response = $this->actingAs($follower) 58 | ->getJson("/api/articles/{$article->slug}/comments"); 59 | 60 | $response->assertOk() 61 | ->assertJsonPath('comments.0.author.following', true); 62 | } 63 | 64 | public function testListArticleCommentsUnfollowedAuthor(): void 65 | { 66 | /** @var User $user */ 67 | $user = User::factory()->create(); 68 | /** @var Article $article */ 69 | $article = Article::factory() 70 | ->has(Comment::factory(), 'comments') 71 | ->create(); 72 | 73 | $response = $this->actingAs($user) 74 | ->getJson("/api/articles/{$article->slug}/comments"); 75 | 76 | $response->assertOk() 77 | ->assertJsonPath('comments.0.author.following', false); 78 | } 79 | 80 | public function testListEmptyArticleComments(): void 81 | { 82 | /** @var Article $article */ 83 | $article = Article::factory()->create(); 84 | 85 | $response = $this->getJson("/api/articles/{$article->slug}/comments"); 86 | 87 | $response->assertOk() 88 | ->assertExactJson(['comments' => []]); 89 | } 90 | 91 | public function testListCommentsOfNonExistentArticle(): void 92 | { 93 | $this->getJson('/api/articles/non-existent/comments') 94 | ->assertNotFound(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /tests/Feature/Api/Favorites/AddFavoritesTest.php: -------------------------------------------------------------------------------- 1 | create(); 19 | $this->user = $user; 20 | } 21 | 22 | public function testAddArticleToFavorites(): void 23 | { 24 | /** @var Article $article */ 25 | $article = Article::factory()->create(); 26 | 27 | $response = $this->actingAs($this->user) 28 | ->postJson("/api/articles/{$article->slug}/favorite"); 29 | $response->assertOk() 30 | ->assertJsonPath('article.favorited', true) 31 | ->assertJsonPath('article.favoritesCount', 1); 32 | 33 | $this->assertTrue($this->user->favorites->contains($article)); 34 | 35 | $repeatedResponse = $this->actingAs($this->user) 36 | ->postJson("/api/articles/{$article->slug}/favorite"); 37 | $repeatedResponse->assertOk() 38 | ->assertJsonPath('article.favoritesCount', 1); 39 | 40 | $this->assertDatabaseCount('article_favorite', 1); 41 | } 42 | 43 | public function testAddNonExistentArticleToFavorites(): void 44 | { 45 | $this->actingAs($this->user) 46 | ->postJson('/api/articles/non-existent/favorite') 47 | ->assertNotFound(); 48 | } 49 | 50 | public function testAddArticleToFavoritesWithoutAuth(): void 51 | { 52 | /** @var Article $article */ 53 | $article = Article::factory()->create(); 54 | 55 | $this->postJson("/api/articles/{$article->slug}/favorite") 56 | ->assertUnauthorized(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/Feature/Api/Favorites/RemoveFavoritesTest.php: -------------------------------------------------------------------------------- 1 | create(); 19 | $this->user = $user; 20 | } 21 | 22 | public function testRemoveArticleFromFavorites(): void 23 | { 24 | /** @var Article $article */ 25 | $article = Article::factory() 26 | ->hasAttached($this->user, [], 'favoredUsers') 27 | ->create(); 28 | 29 | $response = $this->actingAs($this->user) 30 | ->deleteJson("/api/articles/{$article->slug}/favorite"); 31 | $response->assertOk() 32 | ->assertJsonPath('article.favorited', false) 33 | ->assertJsonPath('article.favoritesCount', 0); 34 | 35 | $this->assertTrue($this->user->favorites->doesntContain($article)); 36 | 37 | $this->actingAs($this->user) 38 | ->deleteJson("/api/articles/{$article->slug}/favorite") 39 | ->assertOk(); 40 | } 41 | 42 | public function testRemoveNonExistentArticleFromFavorites(): void 43 | { 44 | $this->actingAs($this->user) 45 | ->deleteJson('/api/articles/non-existent/favorite') 46 | ->assertNotFound(); 47 | } 48 | 49 | public function testRemoveArticleFromFavoritesWithoutAuth(): void 50 | { 51 | /** @var Article $article */ 52 | $article = Article::factory()->create(); 53 | 54 | $this->deleteJson("/api/articles/{$article->slug}/favorite") 55 | ->assertUnauthorized(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /tests/Feature/Api/Profile/FollowProfileTest.php: -------------------------------------------------------------------------------- 1 | create(); 18 | $this->user = $user; 19 | } 20 | 21 | public function testFollowProfile(): void 22 | { 23 | /** @var User $follower */ 24 | $follower = User::factory()->create(); 25 | 26 | $response = $this->actingAs($follower) 27 | ->postJson("/api/profiles/{$this->user->username}/follow"); 28 | $response->assertOk() 29 | ->assertJsonPath('profile.following', true); 30 | 31 | $this->assertTrue($this->user->followers->contains($follower)); 32 | 33 | $this->actingAs($follower) 34 | ->postJson("/api/profiles/{$this->user->username}/follow") 35 | ->assertOk(); 36 | 37 | $this->assertDatabaseCount('author_follower', 1); 38 | } 39 | 40 | public function testFollowProfileWithoutAuth(): void 41 | { 42 | $this->postJson("/api/profiles/{$this->user->username}/follow") 43 | ->assertUnauthorized(); 44 | } 45 | 46 | public function testFollowNonExistentProfile(): void 47 | { 48 | $this->actingAs($this->user) 49 | ->postJson('/api/profiles/non-existent/follow') 50 | ->assertNotFound(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/Feature/Api/Profile/ShowProfileTest.php: -------------------------------------------------------------------------------- 1 | create(); 18 | $this->profile = $user; 19 | } 20 | 21 | public function testShowProfileWithoutAuth(): void 22 | { 23 | /** @var User $profile */ 24 | $profile = User::factory()->create(); 25 | 26 | $response = $this->getJson("/api/profiles/{$profile->username}"); 27 | 28 | $response->assertOk() 29 | ->assertExactJson([ 30 | 'profile' => [ 31 | 'username' => $profile->username, 32 | 'bio' => $profile->bio, 33 | 'image' => $profile->image, 34 | ], 35 | ]); 36 | } 37 | 38 | public function testShowUnfollowedProfile(): void 39 | { 40 | /** @var User $user */ 41 | $user = User::factory()->create(); 42 | 43 | $response = $this->actingAs($user) 44 | ->getJson("/api/profiles/{$this->profile->username}"); 45 | 46 | $response->assertOk() 47 | ->assertJsonPath('profile.following', false); 48 | } 49 | 50 | public function testShowFollowedProfile(): void 51 | { 52 | /** @var User $user */ 53 | $user = User::factory() 54 | ->hasAttached($this->profile, [], 'authors') 55 | ->create(); 56 | 57 | $response = $this->actingAs($user) 58 | ->getJson("/api/profiles/{$this->profile->username}"); 59 | 60 | $response->assertOk() 61 | ->assertJsonPath('profile.following', true); 62 | } 63 | 64 | public function testShowNonExistentProfile(): void 65 | { 66 | $this->getJson('/api/profiles/non-existent') 67 | ->assertNotFound(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /tests/Feature/Api/Profile/UnfollowProfileTest.php: -------------------------------------------------------------------------------- 1 | create(); 18 | $this->user = $user; 19 | } 20 | 21 | public function testUnfollowProfile(): void 22 | { 23 | /** @var User $follower */ 24 | $follower = User::factory() 25 | ->hasAttached($this->user, [], 'authors') 26 | ->create(); 27 | 28 | $response = $this->actingAs($follower) 29 | ->deleteJson("/api/profiles/{$this->user->username}/follow"); 30 | $response->assertOk() 31 | ->assertJsonPath('profile.following', false); 32 | 33 | $this->assertTrue($this->user->followers->doesntContain($follower)); 34 | 35 | $this->actingAs($follower) 36 | ->deleteJson("/api/profiles/{$this->user->username}/follow") 37 | ->assertOk(); 38 | } 39 | 40 | public function testUnfollowProfileWithoutAuth(): void 41 | { 42 | $this->deleteJson("/api/profiles/{$this->user->username}/follow") 43 | ->assertUnauthorized(); 44 | } 45 | 46 | public function testUnfollowNonExistentProfile(): void 47 | { 48 | $this->actingAs($this->user) 49 | ->deleteJson('/api/profiles/non-existent/follow') 50 | ->assertNotFound(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/Feature/Api/TagsTest.php: -------------------------------------------------------------------------------- 1 | count(5)->create(); 15 | 16 | $response = $this->getJson('/api/tags'); 17 | 18 | $response->assertOk() 19 | ->assertExactJson([ 20 | 'tags' => $tags->pluck('name'), 21 | ]); 22 | } 23 | 24 | public function testReturnsEmptyTagsList(): void 25 | { 26 | $response = $this->getJson('/api/tags'); 27 | 28 | $response->assertOk() 29 | ->assertExactJson(['tags' => []]); 30 | } 31 | 32 | public function testTagResource(): void 33 | { 34 | /** @var Tag $tag */ 35 | $tag = Tag::factory()->create(); 36 | 37 | $resource = new TagResource($tag); 38 | 39 | /** @var Request $request */ 40 | $request = $this->mock(Request::class); 41 | 42 | $tagResource = $resource->toArray($request); 43 | 44 | $this->assertSame(['name' => $tag->name], $tagResource); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/Feature/Api/User/ShowUserTest.php: -------------------------------------------------------------------------------- 1 | create(); 16 | 17 | $response = $this->actingAs($user) 18 | ->getJson('/api/user'); 19 | 20 | $response->assertOk() 21 | ->assertJson(fn (AssertableJson $json) => 22 | $json->has('user', fn (AssertableJson $item) => 23 | $item->whereType('token', 'string') 24 | ->whereAll([ 25 | 'username' => $user->username, 26 | 'email' => $user->email, 27 | 'bio' => $user->bio, 28 | 'image' => $user->image, 29 | ]) 30 | ) 31 | ); 32 | 33 | $token = Jwt\Parser::parse($response['user']['token']); 34 | $this->assertTrue(Jwt\Validator::validate($token)); 35 | } 36 | 37 | public function testShowUserWithoutAuth(): void 38 | { 39 | $this->getJson('/api/user') 40 | ->assertUnauthorized(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/Feature/Api/User/UpdateUserTest.php: -------------------------------------------------------------------------------- 1 | create(); 19 | $this->user = $user; 20 | } 21 | 22 | public function testUpdateUser(): void 23 | { 24 | $this->assertNotEquals($username = 'new.username', $this->user->username); 25 | $this->assertNotEquals($email = 'newEmail@example.com', $this->user->email); 26 | $this->assertNotEquals($bio = 'New bio information.', $this->user->bio); 27 | $this->assertNotEquals($image = 'https://example.com/image.png', $this->user->image); 28 | 29 | // update by one to check required_without_all rule 30 | $this->actingAs($this->user) 31 | ->putJson('/api/user', ['user' => ['username' => $username]]) 32 | ->assertOk(); 33 | $this->actingAs($this->user) 34 | ->putJson('/api/user', ['user' => ['email' => $email]]) 35 | ->assertOk(); 36 | $this->actingAs($this->user) 37 | ->putJson('/api/user', ['user' => ['bio' => $bio]]); 38 | $response = $this->actingAs($this->user) 39 | ->putJson('/api/user', ['user' => ['image' => $image]]); 40 | 41 | $response->assertOk() 42 | ->assertJson(fn (AssertableJson $json) => 43 | $json->has('user', fn (AssertableJson $item) => 44 | $item->whereType('token', 'string') 45 | ->whereAll([ 46 | 'username' => $username, 47 | 'email' => $email, 48 | 'bio' => $bio, 49 | 'image' => $image, 50 | ]) 51 | ) 52 | ); 53 | } 54 | 55 | /** 56 | * @dataProvider userProvider 57 | * @param array $data 58 | * @param string|array $errors 59 | */ 60 | public function testUpdateUserValidation(array $data, $errors): void 61 | { 62 | $response = $this->actingAs($this->user) 63 | ->putJson('/api/user', $data); 64 | 65 | $response->assertUnprocessable() 66 | ->assertInvalid($errors); 67 | } 68 | 69 | public function testUpdateUserValidationUnique(): void 70 | { 71 | /** @var User $anotherUser */ 72 | $anotherUser = User::factory()->create(); 73 | 74 | $response = $this->actingAs($this->user) 75 | ->putJson('/api/user', [ 76 | 'user' => [ 77 | 'username' => $anotherUser->username, 78 | 'email' => $anotherUser->email, 79 | ], 80 | ]); 81 | 82 | $response->assertUnprocessable() 83 | ->assertInvalid(['username', 'email']); 84 | } 85 | 86 | public function testSelfUpdateUserValidationUnique(): void 87 | { 88 | $response = $this->actingAs($this->user) 89 | ->putJson('/api/user', [ 90 | 'user' => [ 91 | 'username' => $this->user->username, 92 | 'email' => $this->user->email, 93 | ], 94 | ]); 95 | 96 | $response->assertOk(); 97 | } 98 | 99 | public function testUpdateUserSetNull(): void 100 | { 101 | /** @var User $user */ 102 | $user = User::factory() 103 | ->state([ 104 | 'bio' => 'not-null', 105 | 'image' => 'https://example.com/image.png', 106 | ]) 107 | ->create(); 108 | 109 | $response = $this->actingAs($user) 110 | ->putJson('/api/user', [ 111 | 'user' => [ 112 | 'bio' => null, 113 | 'image' => null, 114 | ], 115 | ]); 116 | 117 | $response->assertOk() 118 | ->assertJsonPath('user.bio', null) 119 | ->assertJsonPath('user.image', null); 120 | } 121 | 122 | public function testUpdateUserWithoutAuth(): void 123 | { 124 | $this->putJson('/api/user') 125 | ->assertUnauthorized(); 126 | } 127 | 128 | /** 129 | * @return array> 130 | */ 131 | public function userProvider(): array 132 | { 133 | $strErrors = ['username', 'email']; 134 | $allErrors = array_merge($strErrors, ['bio', 'image']); 135 | 136 | return [ 137 | 'required' => [[], 'any'], 138 | 'wrong type' => [[ 139 | 'user' => [ 140 | 'username' => 123, 141 | 'email' => null, 142 | 'bio' => [], 143 | 'image' => 123.0, 144 | ], 145 | ], $allErrors], 146 | 'empty strings' => [[ 147 | 'user' => [ 148 | 'username' => '', 149 | 'email' => '', 150 | ], 151 | ], $strErrors], 152 | 'bad username' => [['user' => ['username' => 'user n@me']], 'username'], 153 | 'not email' => [['user' => ['email' => 'not an email']], 'email'], 154 | 'not url' => [['user' => ['image' => 'string']], 'image'], 155 | ]; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /tests/Feature/Jwt/JwtValidatorTest.php: -------------------------------------------------------------------------------- 1 | getToken(); 17 | 18 | $this->assertFalse(Validator::validate($token)); 19 | } 20 | 21 | public function testValidateInvalidSignature(): void 22 | { 23 | $token = Builder::build()->getToken(); 24 | 25 | $token->setUserSignature('string'); 26 | 27 | $this->assertFalse(Validator::validate($token)); 28 | } 29 | 30 | public function testValidateHeaders(): void 31 | { 32 | $token = Builder::build() 33 | ->withHeader('typ', 'string') 34 | ->getToken(); 35 | 36 | $token->setUserSignature(Generator::signature($token)); 37 | 38 | $this->assertFalse(Validator::validate($token)); 39 | } 40 | 41 | public function testValidateZeroExpiration(): void 42 | { 43 | $token = Builder::build()->getToken(); 44 | 45 | $token->setUserSignature(Generator::signature($token)); 46 | 47 | $this->assertFalse(Validator::validate($token)); 48 | } 49 | 50 | public function testValidateExpiration(): void 51 | { 52 | $previousDay = (int) Carbon::now()->subDay()->timestamp; 53 | $token = Builder::build() 54 | ->expiresAt($previousDay) 55 | ->getToken(); 56 | 57 | $token->setUserSignature(Generator::signature($token)); 58 | 59 | $this->assertFalse(Validator::validate($token)); 60 | } 61 | 62 | public function testValidateNonExistentUser(): void 63 | { 64 | $previousDay = Carbon::now()->addDay()->unix(); 65 | $token = Builder::build() 66 | ->expiresAt($previousDay) 67 | ->withClaim('sub', 123) 68 | ->getToken(); 69 | 70 | $token->setUserSignature(Generator::signature($token)); 71 | 72 | $this->assertFalse(Validator::validate($token)); 73 | } 74 | 75 | public function testValidateToken(): void 76 | { 77 | $user = User::factory()->create(); 78 | $previousDay = (int) Carbon::now()->addDay()->timestamp; 79 | 80 | $token = Builder::build() 81 | ->expiresAt($previousDay) 82 | ->subject($user) 83 | ->getToken(); 84 | 85 | $token->setUserSignature(Generator::signature($token)); 86 | 87 | $this->assertTrue(Validator::validate($token)); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | expectException(JwtParseException::class); 15 | 16 | Parser::parse('string'); 17 | } 18 | 19 | public function testParseNotBase64(): void 20 | { 21 | $this->expectException(JwtParseException::class); 22 | 23 | Parser::parse('string@.string#.string*'); 24 | } 25 | 26 | public function testParseNotJson(): void 27 | { 28 | $this->expectException(JsonException::class); 29 | 30 | Parser::parse('b25l.dHdv.dGhyZWU='); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /webpack.mix.js: -------------------------------------------------------------------------------- 1 | const mix = require('laravel-mix'); 2 | 3 | /* 4 | |-------------------------------------------------------------------------- 5 | | Mix Asset Management 6 | |-------------------------------------------------------------------------- 7 | | 8 | | Mix provides a clean, fluent API for defining some Webpack build steps 9 | | for your Laravel applications. By default, we are compiling the CSS 10 | | file for the application as well as bundling up all the JS files. 11 | | 12 | */ 13 | 14 | mix.js('resources/js/app.js', 'public/js') 15 | .postCss('resources/css/app.css', 'public/css', [ 16 | // 17 | ]); 18 | --------------------------------------------------------------------------------