Completed
Pull Request — master (#2014)
by Song
02:47
created

AuthController::guard()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Encore\Admin\Controllers;
4
5
use Encore\Admin\Auth\Database\Administrator;
6
use Encore\Admin\Facades\Admin;
7
use Encore\Admin\Form;
8
use Encore\Admin\Layout\Content;
9
use Illuminate\Http\Request;
10
use Illuminate\Routing\Controller;
11
use Illuminate\Support\Facades\Auth;
12
use Illuminate\Support\Facades\Lang;
13
use Illuminate\Support\Facades\Redirect;
14
use Illuminate\Support\Facades\Validator;
15
16
class AuthController extends Controller
17
{
18
    /**
19
     * Show the login page.
20
     *
21
     * @return \Illuminate\Contracts\View\Factory|Redirect|\Illuminate\View\View
22
     */
23
    public function getLogin()
24
    {
25
        if ($this->guard()->check()) {
26
            return redirect($this->redirectPath());
27
        }
28
29
        return view('admin::login');
30
    }
31
32
    /**
33
     * Handle a login request.
34
     *
35
     * @param Request $request
36
     *
37
     * @return mixed
38
     */
39
    public function postLogin(Request $request)
40
    {
41
        $credentials = $request->only([$this->username(), 'password']);
42
43
        /** @var \Illuminate\Validation\Validator $validator */
44
        $validator = Validator::make($credentials, [
45
            $this->username()   => 'required',
46
            'password'          => 'required',
47
        ]);
48
49
        if ($validator->fails()) {
50
            return back()->withInput()->withErrors($validator);
51
        }
52
53
        if ($this->guard()->attempt($credentials)) {
54
            return $this->sendLoginResponse($request);
55
        }
56
57
        return back()->withInput()->withErrors([
58
            $this->username() => $this->getFailedLoginMessage(),
59
        ]);
60
    }
61
62
    /**
63
     * User logout.
64
     *
65
     * @return Redirect
66
     */
67
    public function getLogout(Request $request)
68
    {
69
        $this->guard()->logout();
70
71
        $request->session()->invalidate();
72
73
        return redirect(config('admin.route.prefix'));
74
    }
75
76
    /**
77
     * User setting page.
78
     *
79
     * @return mixed
80
     */
81
    public function getSetting()
82
    {
83
        return Admin::content(function (Content $content) {
84
            $content->header(trans('admin.user_setting'));
85
            $form = $this->settingForm();
86
            $form->tools(
87
                function (Form\Tools $tools) {
88
                    $tools->disableBackButton();
89
                    $tools->disableListButton();
90
                }
91
            );
92
            $content->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...
93
        });
94
    }
95
96
    /**
97
     * Update user setting.
98
     *
99
     * @return \Symfony\Component\HttpFoundation\Response
100
     */
101
    public function putSetting()
102
    {
103
        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...
104
    }
105
106
    /**
107
     * Model-form for user setting.
108
     *
109
     * @return Form
110
     */
111
    protected function settingForm()
112
    {
113
        return Administrator::form(function (Form $form) {
114
            $form->display('username', trans('admin.username'));
115
            $form->text('name', trans('admin.name'))->rules('required');
116
            $form->image('avatar', trans('admin.avatar'));
117
            $form->password('password', trans('admin.password'))->rules('confirmed|required');
118
            $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
119
                ->default(function ($form) {
120
                    return $form->model()->password;
121
                });
122
123
            $form->setAction(admin_base_path('auth/setting'));
124
125
            $form->ignore(['password_confirmation']);
126
127 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...
128
                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...
129
                    $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...
130
                }
131
            });
132
133
            $form->saved(function () {
134
                admin_toastr(trans('admin.update_succeeded'));
135
136
                return redirect(admin_base_path('auth/setting'));
137
            });
138
        });
139
    }
140
141
    /**
142
     * @return string|\Symfony\Component\Translation\TranslatorInterface
143
     */
144
    protected function getFailedLoginMessage()
145
    {
146
        return Lang::has('auth.failed')
147
            ? trans('auth.failed')
148
            : 'These credentials do not match our records.';
149
    }
150
151
    /**
152
     * Get the post login redirect path.
153
     *
154
     * @return string
155
     */
156
    protected function redirectPath()
157
    {
158
        if (method_exists($this, 'redirectTo')) {
159
            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...
160
        }
161
162
        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...
163
    }
164
165
    /**
166
     * Send the response after the user was authenticated.
167
     *
168
     * @param \Illuminate\Http\Request $request
169
     *
170
     * @return \Illuminate\Http\Response
171
     */
172
    protected function sendLoginResponse(Request $request)
173
    {
174
        admin_toastr(trans('admin.login_successful'));
175
176
        $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...
177
178
        return redirect()->intended($this->redirectPath());
179
    }
180
181
    /**
182
     * Get the login username to be used by the controller.
183
     *
184
     * @return string
185
     */
186
    protected function username()
187
    {
188
        return 'username';
189
    }
190
191
    /**
192
     * Get the guard to be used during authentication.
193
     *
194
     * @return \Illuminate\Contracts\Auth\StatefulGuard
195
     */
196
    protected function guard()
197
    {
198
        return Auth::guard('admin');
199
    }
200
}
201