UserController::authenticated()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
namespace App\Http\Controllers\Front;
4
5
use App\Http\Requests\Front\RegisterRequest;
6
use App\Model\Front\UserAuth;
7
use App\Repository\Front\UserRepository;
8
use Illuminate\Foundation\Auth\AuthenticatesUsers;
9
use Illuminate\Http\Request;
10
use App\Http\Requests\Front\LoginRequest;
11
use App\Model\Front\User;
12
use Auth;
13
use Overtrue\Socialite\AuthorizeFailedException;
14
use Overtrue\Socialite\InvalidStateException;
15
use Overtrue\Socialite\SocialiteManager;
16
use Illuminate\Auth\Events\Registered;
17
18
class UserController extends BaseController
19
{
20
    use AuthenticatesUsers;
0 ignored issues
show
introduced by
The trait Illuminate\Foundation\Auth\AuthenticatesUsers requires some properties which are not provided by App\Http\Controllers\Front\UserController: $redirectTo, $maxAttempts, $decayMinutes
Loading history...
21
22
    protected $guard = 'member';
23
24
    const AUTH_SESSION = 'auth_login_user';
25
26
    /**
27
     * Create a new controller instance.
28
     *
29
     * @return void
30
     */
31
    public function __construct()
32
    {
33
        $this->middleware('guest:' . $this->guard)->except('logout');
34
    }
35
36
    /**
37
     * 用户登录页面
38
     *
39
     * @return \Illuminate\View\View
40
     */
41
    public function showLogin()
42
    {
43
        $url = url()->previous();
44
        if ($url === route('member::logout')) {
45
            $url = '/';
46
        }
47
48
        return view('front.user.login', compact('url'));
49
    }
50
51
    /**
52
     * 用户登录
53
     *
54
     * @param LoginRequest $request
55
     * @throws \Exception
56
     * @return mixed
57
     */
58
    public function login(LoginRequest $request)
59
    {
60
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
61
        // the login attempts for this application. We'll key this by the username and
62
        // the IP address of the client making these requests into this application.
63
        if ($this->hasTooManyLoginAttempts($request)) {
64
            $this->fireLockoutEvent($request);
65
66
            return $this->sendLockoutResponse($request);
67
        }
68
69
        // 检查用户是否已被禁用
70
        $user = $this->guard()->getProvider()->retrieveByCredentials($this->credentials($request));
71
        if ($user && $user->status == User::STATUS_DISABLE) {
72
            return [
73
                'code' => 1,
74
                'msg' => '用户被禁用'
75
            ];
76
        }
77
78
        if ($this->attemptLogin($request)) {
79
            // 如果存在三方登录关联,则关联之
80
            $this->associateAuth($user);
81
82
            return $this->sendLoginResponse($request);
83
        }
84
85
        // If the login attempt was unsuccessful we will increment the number of attempts
86
        // to login and redirect the user back to the login form. Of course, when this
87
        // user surpasses their maximum number of attempts they will get locked out.
88
        $this->incrementLoginAttempts($request);
89
90
        return $this->sendFailedLoginResponse($request);
91
    }
92
93
    /**
94
     * 退出登录
95
     *
96
     * @param Request $request
97
     */
98
    public function logout(Request $request)
99
    {
100
        $this->guard()->logout();
101
102
        $request->session()->invalidate();
103
104
        return redirect(route('member::login.show'));
105
    }
106
107
    public function guard()
108
    {
109
        return Auth::guard($this->guard);
110
    }
111
112
    public function username()
113
    {
114
        return 'phone';
115
    }
116
117
    protected function authenticated(Request $request, $user)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

117
    protected function authenticated(/** @scrutinizer ignore-unused */ Request $request, $user)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $user is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

117
    protected function authenticated(Request $request, /** @scrutinizer ignore-unused */ $user)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
118
    {
119
        return [
120
            'code' => 0,
121
            'msg' => '登陆成功',
122
            'redirect' => true
123
        ];
124
    }
125
126
    public function showRegistrationForm()
127
    {
128
        return view('front.user.login');
129
    }
130
131
    public function register(RegisterRequest $request)
132
    {
133
        event(
134
            new Registered(
135
                $user = UserRepository::create($request->only(['phone', 'password', 'name']))
136
            )
137
        );
138
139
        $this->associateAuth($user);
140
        $this->guard()->login($user);
141
142
        return [
143
            'code' => 0,
144
            'msg' => '注册成功',
145
            'redirect' => true
146
        ];
147
    }
148
149
    public function weiboAuth()
150
    {
151
        $socialite = new SocialiteManager(config('light.auth_login'));
152
        return $socialite->driver('weibo')->redirect();
153
    }
154
155
    public function weiboCallback()
156
    {
157
        return $this->handleCallback('weibo');
158
    }
159
160
    public function qqAuth()
161
    {
162
        $socialite = new SocialiteManager(config('light.auth_login'));
163
        return $socialite->driver('qq')->redirect();
164
    }
165
166
    public function qqCallback()
167
    {
168
        return $this->handleCallback('qq');
169
    }
170
171
    public function wechatAuth()
172
    {
173
        $socialite = new SocialiteManager(config('light.auth_login'));
174
        return $socialite->driver('wechat')->redirect();
175
    }
176
177
    public function wechatCallback()
178
    {
179
        return $this->handleCallback('wechat');
180
    }
181
182
    protected function associateAuth($user)
183
    {
184
        $authUser = session()->pull(self::AUTH_SESSION);
185
        if ($authUser instanceof \Overtrue\Socialite\User &&
186
            UserAuth::where('openid', (string) $authUser->getId())->first() === null
187
        ) {
188
            UserRepository::createAuth($user->id, $authUser);
189
        }
190
    }
191
192
    protected function handleCallback($type)
193
    {
194
        try {
195
            $socialite = new SocialiteManager(config('light.auth_login'));
196
            $user = $socialite->driver($type)->user();
197
198
            $openId = (string)$user->getId();
199
            $siteUser = UserAuth::query()->where('openid', $openId)->first();
200
            if ($siteUser) {
201
                $this->guard()->loginUsingId($siteUser->user_id);
202
                return redirect()->intended('/');
203
            }
204
205
            // 重定向到登录注册页面,关联本站用户
206
            session([self::AUTH_SESSION => $user]);
207
            return redirect(route('member::login.show'));
208
        } catch (AuthorizeFailedException $e) {
209
            return redirect(route('member::login.show'))->withErrors('授权失败');
210
        } catch (InvalidStateException $e) {
211
            return redirect(route('member::login.show'))->withErrors('invalid state');
212
        }
213
    }
214
}
215