Completed
Push — master ( 002d5b...7b9308 )
by Song
02:19
created

AuthController::loginValidator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Controllers;
4
5
use Encore\Admin\Facades\Admin;
6
use Encore\Admin\Form;
7
use Encore\Admin\Layout\Content;
8
use Illuminate\Http\Request;
9
use Illuminate\Routing\Controller;
10
use Illuminate\Support\Facades\Auth;
11
use Illuminate\Support\Facades\Lang;
12
use Illuminate\Support\Facades\Redirect;
13
use Illuminate\Support\Facades\Validator;
14
15
class AuthController extends Controller
16
{
17
    /**
18
     * @var string
19
     */
20
    protected $loginView = 'admin::login';
21
22
    /**
23
     * Show the login page.
24
     *
25
     * @return \Illuminate\Contracts\View\Factory|Redirect|\Illuminate\View\View
26
     */
27
    public function getLogin()
28
    {
29
        if ($this->guard()->check()) {
30
            return redirect($this->redirectPath());
31
        }
32
33
        return view($this->loginView);
34
    }
35
36
    /**
37
     * Handle a login request.
38
     *
39
     * @param Request $request
40
     *
41
     * @return mixed
42
     */
43
    public function postLogin(Request $request)
44
    {
45
        $this->loginValidator($request->all())->validate();
46
47
        $credentials = $request->only([$this->username(), 'password']);
48
        $remember = $request->get('remember', false);
49
50
        if ($this->guard()->attempt($credentials, $remember)) {
51
            return $this->sendLoginResponse($request);
52
        }
53
54
        return back()->withInput()->withErrors([
55
            $this->username() => $this->getFailedLoginMessage(),
56
        ]);
57
    }
58
59
    /**
60
     * Get a validator for an incoming login request.
61
     *
62
     * @param  array  $data
63
     * @return \Illuminate\Contracts\Validation\Validator
64
     */
65
    protected function loginValidator(array $data)
66
    {
67
        return Validator::make($data, [
68
            $this->username()   => 'required',
69
            'password'          => 'required',
70
        ]);
71
    }
72
73
    /**
74
     * User logout.
75
     *
76
     * @return Redirect
77
     */
78
    public function getLogout(Request $request)
79
    {
80
        $this->guard()->logout();
81
82
        $request->session()->invalidate();
83
84
        return redirect(config('admin.route.prefix'));
85
    }
86
87
    /**
88
     * User setting page.
89
     *
90
     * @param Content $content
91
     *
92
     * @return Content
93
     */
94
    public function getSetting(Content $content)
95
    {
96
        $form = $this->settingForm();
97
        $form->tools(
98
            function (Form\Tools $tools) {
99
                $tools->disableList();
100
            }
101
        );
102
103
        return $content
104
            ->header(trans('admin.user_setting'))
105
            ->body($form->edit(Admin::user()->id));
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
106
    }
107
108
    /**
109
     * Update user setting.
110
     *
111
     * @return \Symfony\Component\HttpFoundation\Response
112
     */
113
    public function putSetting()
114
    {
115
        return $this->settingForm()->update(Admin::user()->id);
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
116
    }
117
118
    /**
119
     * Model-form for user setting.
120
     *
121
     * @return Form
122
     */
123
    protected function settingForm()
124
    {
125
        $class = config('admin.database.users_model');
126
127
        $form = new Form(new $class());
128
129
        $form->display('username', trans('admin.username'));
130
        $form->text('name', trans('admin.name'))->rules('required');
131
        $form->image('avatar', trans('admin.avatar'));
132
        $form->password('password', trans('admin.password'))->rules('confirmed|required');
133
        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
134
            ->default(function ($form) {
135
                return $form->model()->password;
136
            });
137
138
        $form->setAction(admin_base_path('auth/setting'));
139
140
        $form->ignore(['password_confirmation']);
141
142 View Code Duplication
        $form->saving(function (Form $form) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
143
            if ($form->password && $form->model()->password != $form->password) {
0 ignored issues
show
Documentation introduced by
The property password does not exist on object<Encore\Admin\Form>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
144
                $form->password = bcrypt($form->password);
0 ignored issues
show
Documentation introduced by
The property password does not exist on object<Encore\Admin\Form>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
The property password does not exist on object<Encore\Admin\Form>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
145
            }
146
        });
147
148
        $form->saved(function () {
149
            admin_toastr(trans('admin.update_succeeded'));
150
151
            return redirect(admin_base_path('auth/setting'));
152
        });
153
154
        return $form;
155
    }
156
157
    /**
158
     * @return string|\Symfony\Component\Translation\TranslatorInterface
159
     */
160
    protected function getFailedLoginMessage()
161
    {
162
        return Lang::has('auth.failed')
163
            ? trans('auth.failed')
164
            : 'These credentials do not match our records.';
165
    }
166
167
    /**
168
     * Get the post login redirect path.
169
     *
170
     * @return string
171
     */
172
    protected function redirectPath()
173
    {
174
        if (method_exists($this, 'redirectTo')) {
175
            return $this->redirectTo();
0 ignored issues
show
Documentation Bug introduced by
The method redirectTo does not exist on object<Encore\Admin\Controllers\AuthController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
176
        }
177
178
        return property_exists($this, 'redirectTo') ? $this->redirectTo : config('admin.route.prefix');
0 ignored issues
show
Bug introduced by
The property redirectTo does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
179
    }
180
181
    /**
182
     * Send the response after the user was authenticated.
183
     *
184
     * @param \Illuminate\Http\Request $request
185
     *
186
     * @return \Illuminate\Http\Response
187
     */
188
    protected function sendLoginResponse(Request $request)
189
    {
190
        admin_toastr(trans('admin.login_successful'));
191
192
        $request->session()->regenerate();
0 ignored issues
show
Bug introduced by
The method regenerate() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
193
194
        return redirect()->intended($this->redirectPath());
195
    }
196
197
    /**
198
     * Get the login username to be used by the controller.
199
     *
200
     * @return string
201
     */
202
    protected function username()
203
    {
204
        return 'username';
205
    }
206
207
    /**
208
     * Get the guard to be used during authentication.
209
     *
210
     * @return \Illuminate\Contracts\Auth\StatefulGuard
211
     */
212
    protected function guard()
213
    {
214
        return Auth::guard('admin');
215
    }
216
}
217