diff options
author | Camil Staps | 2016-09-04 23:30:15 +0200 |
---|---|---|
committer | Camil Staps | 2016-09-04 23:30:15 +0200 |
commit | c61b156f1bd93ec4aadd8adc78523b42b0232918 (patch) | |
tree | cd9bcb6f889dcf554818246957bed54eb14c9fbe | |
parent | Use blade templates (diff) |
User creation and authentication
-rw-r--r-- | app/Http/Controllers/UserController.php | 67 | ||||
-rw-r--r-- | app/Http/Middleware/Authenticate.php | 45 | ||||
-rw-r--r-- | app/Http/routes.php | 56 | ||||
-rw-r--r-- | app/Observers/UserObserver.php | 34 | ||||
-rw-r--r-- | app/Providers/AppServiceProvider.php | 25 | ||||
-rw-r--r-- | app/Providers/AuthServiceProvider.php | 39 | ||||
-rw-r--r-- | app/User.php | 82 | ||||
-rw-r--r-- | bootstrap/app.php | 14 | ||||
-rw-r--r-- | composer.json | 4 | ||||
-rw-r--r-- | config/auth.php | 88 | ||||
-rw-r--r-- | config/mail.php | 115 | ||||
-rw-r--r-- | database/migrations/2016_09_04_081740_create_users_table.php | 33 | ||||
-rw-r--r-- | resources/views/layouts/master.blade.php | 11 | ||||
-rw-r--r-- | resources/views/mails/user/create.blade.php | 13 | ||||
-rw-r--r-- | resources/views/shared/already_logged_in.blade.php | 1 | ||||
-rw-r--r-- | resources/views/shared/messages.blade.php | 5 | ||||
-rw-r--r-- | resources/views/user/create.blade.php | 30 |
17 files changed, 622 insertions, 40 deletions
diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php new file mode 100644 index 0000000..7036439 --- /dev/null +++ b/app/Http/Controllers/UserController.php @@ -0,0 +1,67 @@ +<?php +/** + * HebrewParseTrainer - practice Hebrew verbs + * Copyright (C) 2015 Camil Staps <info@camilstaps.nl> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +namespace App\Http\Controllers; + +use Illuminate\Http\Request; +use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\ValidationException; +use Laravel\Lumen\Routing\Controller as BaseController; + +use HebrewParseTrainer\User; + +class UserController extends BaseController { + + public function createForm(Request $request) { + $messages = []; + + if ($request->isMethod('post')) { + $validator = Validator::make($request->input(), [ + 'email' => 'required|unique:users|email', + 'name' => 'required|unique:users', + 'password' => 'required|confirmed|min:8', + ]); + + if ($validator->fails()) { + foreach ($validator->errors()->all() as $error) { + $messages[] = ['danger', $error]; + } + } else { + $user = new User; + $user->name = $request->input('name'); + $user->email = $request->input('email'); + $user->password = $request->input('password'); + if ($user->save()) { + $messages[] = ['success', 'Your account has been created.']; + } else { + $messages[] = ['danger', 'Your account could not be created.']; + } + } + } + + return view('user.create', + [ + 'messages' => $messages, + 'form' => [ + 'email' => $request->input('email'), + 'name' => $request->input('name') + ] + ]); + } + +} diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php new file mode 100644 index 0000000..6db8bb0 --- /dev/null +++ b/app/Http/Middleware/Authenticate.php @@ -0,0 +1,45 @@ +<?php + +namespace App\Http\Middleware; + +use Closure; +use Illuminate\Contracts\Auth\Factory as Auth; + +class Authenticate +{ + /** + * The authentication guard factory instance. + * + * @var \Illuminate\Contracts\Auth\Factory + */ + protected $auth; + + /** + * Create a new middleware instance. + * + * @param \Illuminate\Contracts\Auth\Factory $auth + * @return void + */ + public function __construct(Auth $auth) + { + $this->auth = $auth; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * @param string|null $guard + * @return mixed + */ + public function handle($request, Closure $next, $guard = null) + { + if ($this->auth->guard($guard)->guest()) { + return response('Unauthorized.', 401) + ->header('WWW-Authenticate', 'Basic realm="Please enter your email and password"'); + } + + return $next($request); + } +} diff --git a/app/Http/routes.php b/app/Http/routes.php index 67b661b..9cf12b4 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -28,24 +28,40 @@ | */ -$app->group(['prefix' => parse_url(env('APP_URL'), PHP_URL_PATH)], function ($app) { - - $app->get('/', function () use ($app) { - return view('trainer'); - }); - - $app->get('/stem', function () use ($app) { - return \HebrewParseTrainer\Stem::all(); - }); - - $app->get('/tense', function () use ($app) { - return \HebrewParseTrainer\Tense::all(); - }); - - $app->get('/verb/random', 'App\Http\Controllers\RandomVerbController@show'); - - $app->get('/stats', function () use ($app) { - return view('stats'); - }); - +$app->group( + ['prefix' => parse_url(env('APP_URL'), PHP_URL_PATH)], + function ($app) { + + $app->get('/', function () use ($app) { + return view('trainer'); + }); + + $app->get('/stem', function () use ($app) { + return \HebrewParseTrainer\Stem::all(); + }); + + $app->get('/tense', function () use ($app) { + return \HebrewParseTrainer\Tense::all(); + }); + + $app->get('/logout', function () use ($app) { + return response('Unauthorized.', 401) + ->header('WWW-Authenticate', 'Basic realm="Please click OK, then Cancel to logout."'); + }); + + $app->get('/verb/random', 'App\Http\Controllers\RandomVerbController@show'); + + $app->get('/user/create', 'App\Http\Controllers\UserController@createForm'); + $app->post('/user/create', 'App\Http\Controllers\UserController@createForm'); + + $app->group( + ['middleware' => 'auth:basic-http'], + function ($app) { + + $app->get('/stats', function () use ($app) { + return view('stats'); + }); + + }); + }); diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php new file mode 100644 index 0000000..0989bb2 --- /dev/null +++ b/app/Observers/UserObserver.php @@ -0,0 +1,34 @@ +<?php +/** + * HebrewParseTrainer - practice Hebrew verbs + * Copyright (C) 2015 Camil Staps <info@camilstaps.nl> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +namespace App\Observers; + +use Illuminate\Support\Facades\Mail; + +use HebrewParseTrainer\User; + +class UserObserver { + + public function created(User $user) { + Mail::plain('mails.user.create', ['user' => $user], function ($msg) { + $msg->to(['info@camilstaps.nl']); + $msg->from(['test@camilstaps.nl']); + }); + } + +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index ddec046..9bc5fd1 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -3,16 +3,23 @@ namespace App\Providers; use Illuminate\Support\ServiceProvider; +use App\Observers\UserObserver; +use HebrewParseTrainer\User; class AppServiceProvider extends ServiceProvider { - /** - * Register any application services. - * - * @return void - */ - public function register() - { - // - } + /** + * Register any application services. + * + * @return void + */ + public function register() + { + $this->app->singleton('mailer', function ($app) { + $app->configure('services'); + return $app->loadComponent('mail', 'Illuminate\Mail\MailServiceProvider', 'mailer'); + }); + + User::observe(UserObserver::class); + } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php new file mode 100644 index 0000000..7cf4b27 --- /dev/null +++ b/app/Providers/AuthServiceProvider.php @@ -0,0 +1,39 @@ +<?php + +namespace App\Providers; + +use App\User; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Gate; +use Illuminate\Support\ServiceProvider; + +class AuthServiceProvider extends ServiceProvider +{ + /** + * Register any application services. + * + * @return void + */ + public function register() + { + // + } + + /** + * Boot the authentication services for the application. + * + * @return void + */ + public function boot() + { + // Here you may define how you wish users to be authenticated for your Lumen + // application. The callback which receives the incoming request instance + // should return either a User instance or null. You're free to obtain + // the User instance via an API token or any other method necessary. + Auth::viaRequest('api', function ($request) { + if ($request->input('api_token')) { + return User::where('api_token', $request->input('api_token'))->first(); + } + }); + } +} diff --git a/app/User.php b/app/User.php new file mode 100644 index 0000000..3c1799d --- /dev/null +++ b/app/User.php @@ -0,0 +1,82 @@ +<?php +/** + * HebrewParseTrainer - practice Hebrew verbs + * Copyright (C) 2015 Camil Staps <info@camilstaps.nl> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +namespace HebrewParseTrainer; + +use Illuminate\Contracts\Auth\Authenticatable; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Hash; + +class User extends Model implements Authenticatable { + + protected $table = 'users'; + public $timestamps = false; + protected $fillable = ['email', 'name']; + + public function changePoints($kind, $change, $verb = null) { + $change = new PointChange; + $change->user = $this->id; + $change->change = $change; + $change->kind = $kind; + $change->verb = is_null($verb) ? null : $verb->id; + $change->save(); + + $this->points += $change; + $this->save(); + } + + public function setPasswordAttribute($pass) { + $this->attributes['password'] = Hash::make($pass); + } + + public function verifyPassword($pass) { + if (!Hash::check($pass, $this->password)) + return false; + + if (Hash::needsRehash($this->password)) { + $this->password = $pass; + $this->save(); + } + + return true; + } + + public function getAuthIdentifierName() { + return $this->email; + } + + public function getAuthIdentifier() { + return $this->id; + } + + public function getAuthPassword() { + return $this->password; + } + + public function getRememberToken() { + return null; + } + + public function setRememberToken($token) { + } + + public function getRememberTokenName() { + return null; + } + +} diff --git a/bootstrap/app.php b/bootstrap/app.php index eae5bcf..04f448e 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -66,9 +66,9 @@ $app->singleton( // // Laravel\Lumen\Http\Middleware\VerifyCsrfToken::class, // ]); -// $app->routeMiddleware([ - -// ]); +$app->routeMiddleware([ + 'auth' => App\Http\Middleware\Authenticate::class, +]); /* |-------------------------------------------------------------------------- @@ -81,9 +81,13 @@ $app->singleton( | */ -// $app->register(App\Providers\AppServiceProvider::class); +$app->register(App\Providers\AppServiceProvider::class); +$app->register(App\Providers\AuthServiceProvider::class); // $app->register(App\Providers\EventServiceProvider::class); +$app->register(Illuminate\Mail\MailServiceProvider::class); +$app->register(Arubacao\BasicAuth\BasicGuardServiceProvider::class); + /* |-------------------------------------------------------------------------- | Load The Application Routes @@ -99,4 +103,6 @@ $app->group(['namespace' => 'App\Http\Controllers'], function ($app) { require __DIR__.'/../app/Http/routes.php'; }); +$app->configure('mail'); + return $app; diff --git a/composer.json b/composer.json index ba85f9d..dee60f3 100644 --- a/composer.json +++ b/composer.json @@ -7,9 +7,11 @@ "require": { "php": ">=5.5.9", "laravel/lumen-framework": "5.2.*", + "illuminate/mail": "5.2.*", "vlucas/phpdotenv": "~2.2", "twbs/bootstrap": "^3.3", - "components/jquery": "^2.1" + "components/jquery": "^2.1", + "arubacao/http-basic-auth-guard": "^1.0" }, "require-dev": { "phpunit/phpunit": "~4.0", diff --git a/config/auth.php b/config/auth.php new file mode 100644 index 0000000..2331863 --- /dev/null +++ b/config/auth.php @@ -0,0 +1,88 @@ +<?php + +return [ + + /* + |-------------------------------------------------------------------------- + | Authentication Defaults + |-------------------------------------------------------------------------- + | + | This option controls the default authentication "guard" and password + | reset options for your application. You may change these defaults + | as required, but they're a perfect start for most applications. + | + */ + + 'defaults' => [ + 'guard' => env('AUTH_GUARD', 'basic-http'), + ], + + /* + |-------------------------------------------------------------------------- + | Authentication Guards + |-------------------------------------------------------------------------- + | + | Next, you may define every authentication guard for your application. + | Of course, a great default configuration has been defined for you + | here which uses session storage and the Eloquent user provider. + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | Supported: "token" + | + */ + + 'guards' => [ + 'basic-http' => ['driver' => 'basic', 'provider' => 'users'], + ], + + /* + |-------------------------------------------------------------------------- + | User Providers + |-------------------------------------------------------------------------- + | + | All authentication drivers have a user provider. This defines how the + | users are actually retrieved out of your database or other storage + | mechanisms used by this application to persist your user's data. + | + | If you have multiple user tables or models you may configure multiple + | sources which represent each model / table. These sources may then + | be assigned to any extra authentication guards you have defined. + | + | Supported: "database", "eloquent" + | + */ + + 'providers' => [ + 'users' => [ + 'driver' => 'eloquent', + 'model' => HebrewParseTrainer\User::class, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Resetting Passwords + |-------------------------------------------------------------------------- + | + | Here you may set the options for resetting passwords including the view + | that is your password reset e-mail. You may also set the name of the + | table that maintains all of the reset tokens for your application. + | + | You may specify multiple password reset configurations if you have more + | than one user table or model in the application and you want to have + | separate password reset settings based on the specific user types. + | + | The expire time is the number of minutes that the reset token should be + | considered valid. This security feature keeps tokens short-lived so + | they have less time to be guessed. You may change this as needed. + | + */ + + 'passwords' => [ + // + ], + +]; diff --git a/config/mail.php b/config/mail.php new file mode 100644 index 0000000..92b3b29 --- /dev/null +++ b/config/mail.php @@ -0,0 +1,115 @@ +<?php + +return [ + + /* + |-------------------------------------------------------------------------- + | Mail Driver + |-------------------------------------------------------------------------- + | + | Laravel supports both SMTP and PHP's "mail" function as drivers for the + | sending of e-mail. You may specify which one you're using throughout + | your application here. By default, Laravel is setup for SMTP mail. + | + | Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", + | "ses", "sparkpost", "log" + | + */ + + 'driver' => env('MAIL_DRIVER', 'smtp'), + + /* + |-------------------------------------------------------------------------- + | SMTP Host Address + |-------------------------------------------------------------------------- + | + | Here you may provide the host address of the SMTP server used by your + | applications. A default option is provided that is compatible with + | the Mailgun mail service which will provide reliable deliveries. + | + */ + + 'host' => env('MAIL_HOST'), + + /* + |-------------------------------------------------------------------------- + | SMTP Host Port + |-------------------------------------------------------------------------- + | + | This is the SMTP port used by your application to deliver e-mails to + | users of the application. Like the host we have set this value to + | stay compatible with the Mailgun e-mail application by default. + | + */ + + 'port' => env('MAIL_PORT', 587), + + /* + |-------------------------------------------------------------------------- + | Global "From" Address + |-------------------------------------------------------------------------- + | + | You may wish for all e-mails sent by your application to be sent from + | the same address. Here, you may specify a name and address that is + | used globally for all e-mails that are sent by your application. + | + */ + + 'from' => [ + 'address' => env('MAIL_FROM_ADDRESS'), + 'name' => env('MAIL_FROM_NAME'), + ], + + /* + |-------------------------------------------------------------------------- + | E-Mail Encryption Protocol + |-------------------------------------------------------------------------- + | + | Here you may specify the encryption protocol that should be used when + | the application send e-mail messages. A sensible default using the + | transport layer security protocol should provide great security. + | + */ + + 'encryption' => env('MAIL_ENCRYPTION', 'tls'), + + /* + |-------------------------------------------------------------------------- + | SMTP Server Username + |-------------------------------------------------------------------------- + | + | If your SMTP server requires a username for authentication, you should + | set it here. This will get used to authenticate with your server on + | connection. You may also set the "password" value below this one. + | + */ + + 'username' => env('MAIL_USERNAME'), + + /* + |-------------------------------------------------------------------------- + | SMTP Server Password + |-------------------------------------------------------------------------- + | + | Here you may set the password required by your SMTP server to send out + | messages from your application. This will be given to the server on + | connection so that the application will be able to send messages. + | + */ + + 'password' => env('MAIL_PASSWORD'), + + /* + |-------------------------------------------------------------------------- + | Sendmail System Path + |-------------------------------------------------------------------------- + | + | When using the "sendmail" driver to send e-mails, we will need to know + | the path to where Sendmail lives on this server. A default path has + | been provided here, which will work well on most of your systems. + | + */ + + 'sendmail' => '/usr/sbin/sendmail -bs', + +]; diff --git a/database/migrations/2016_09_04_081740_create_users_table.php b/database/migrations/2016_09_04_081740_create_users_table.php new file mode 100644 index 0000000..c5586dc --- /dev/null +++ b/database/migrations/2016_09_04_081740_create_users_table.php @@ -0,0 +1,33 @@ +<?php + +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Migrations\Migration; + +class CreateUsersTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('users', function (Blueprint $table) { + $table->increments('id'); + $table->string('email')->unique(); + $table->string('name')->unique(); + $table->string('password'); + $table->integer('points')->default(0); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('users'); + } +} diff --git a/resources/views/layouts/master.blade.php b/resources/views/layouts/master.blade.php index 43c1a24..3c111da 100644 --- a/resources/views/layouts/master.blade.php +++ b/resources/views/layouts/master.blade.php @@ -20,9 +20,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. <head> <meta charset="utf-8"> <title>ParseTrainer</title> - <link rel="stylesheet" href="vendor/twbs/bootstrap/dist/css/bootstrap.min.css"> - <link rel="stylesheet" href="vendor/twbs/bootstrap/dist/css/bootstrap-theme.min.css"> - <link rel="stylesheet" href="public/css/hebrewparsetrainer.css"> + <link rel="stylesheet" href="{{ env('APP_URL') }}vendor/twbs/bootstrap/dist/css/bootstrap.min.css"> + <link rel="stylesheet" href="{{ env('APP_URL') }}public/css/hebrewparsetrainer.css"> </head> <body role="application"> <div class="container" role="main"> @@ -33,8 +32,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. @yield('master-content') </div> - <script src="vendor/components/jquery/jquery.min.js"></script> - <script src="vendor/twbs/bootstrap/dist/js/bootstrap.min.js"></script> - <script src="public/js/hebrewparsetrainer.js"></script> + <script src="{{ env('APP_URL') }}vendor/components/jquery/jquery.min.js"></script> + <script src="{{ env('APP_URL') }}vendor/twbs/bootstrap/dist/js/bootstrap.min.js"></script> + <script src="{{ env('APP_URL') }}public/js/hebrewparsetrainer.js"></script> </body> </html> diff --git a/resources/views/mails/user/create.blade.php b/resources/views/mails/user/create.blade.php new file mode 100644 index 0000000..721ca4f --- /dev/null +++ b/resources/views/mails/user/create.blade.php @@ -0,0 +1,13 @@ +Dear {{ $user->name }}, + +Thank you for creating an account at the Hebrew Parse Trainer. + +You can now login at {{ URL::to('/admin') }}, using your email address and password. + +If you need any help, you can reach us at {{ env('MAIL_FROM_ADDRESS') }}. + +Thank you for your help! + +Best, + +{{ env('MAIL_FROM_NAME') }} diff --git a/resources/views/shared/already_logged_in.blade.php b/resources/views/shared/already_logged_in.blade.php new file mode 100644 index 0000000..37725fa --- /dev/null +++ b/resources/views/shared/already_logged_in.blade.php @@ -0,0 +1 @@ +You are already logged in. diff --git a/resources/views/shared/messages.blade.php b/resources/views/shared/messages.blade.php new file mode 100644 index 0000000..67feae5 --- /dev/null +++ b/resources/views/shared/messages.blade.php @@ -0,0 +1,5 @@ +@if(isset($messages)) +@foreach($messages as $message) + <div class="alert alert-{{{ $message[0] }}}" role="alert">{{{ $message[1] }}}</div> +@endforeach +@endif diff --git a/resources/views/user/create.blade.php b/resources/views/user/create.blade.php new file mode 100644 index 0000000..818a20a --- /dev/null +++ b/resources/views/user/create.blade.php @@ -0,0 +1,30 @@ +@extends('layouts.master') + +@section('master-content') + +@if(Auth::check()) + @include('shared.already_logged_in') +@else + @include('shared.messages') + + <form method="post"> + <div class="form-group"> + <label for="create-user-email">Email address</label> + <input type="email" class="form-control" id="create-user-email" placeholder="Email" name="email" value="{{{ $form['email'] }}}"/> + </div> + <div class="form-group"> + <label for="create-user-name">Username</label> + <input type="text" class="form-control" id="create-user-name" placeholder="Username" name="name" value="{{{ $form['name'] }}}"/> + </div> + <div class="form-group"> + <label for="create-user-pw1">Password</label> + <input type="password" class="form-control" id="create-user-pw1" placeholder="Password" name="password"/> + </div> + <div class="form-group"> + <input type="password" class="form-control" id="create-user-pw2" placeholder="Password (confirmation)" name="password_confirmation"/> + </div> + <button type="submit" class="btn btn-primary">Create account</button> + </form> +@endif + +@endsection |