UserController::index()   F
last analyzed

Complexity

Conditions 13
Paths 408

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 3.2722
c 0
b 0
f 0
cc 13
nc 408
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Fabrica\Http\Api;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Facades\Event;
7
8
use Fabrica\Http\Requests;
9
use Fabrica\Http\Api\Controller;
10
use Fabrica\Events\DelUserEvent;
11
use Fabrica\Acl\Eloquent\Group;
12
13
use Fabrica\ActiveDirectory\Eloquent\Directory;
14
15
use Maatwebsite\Excel\Facades\Excel;
16
use Cartalyst\Sentinel\Users\EloquentUser;
17
use Sentinel;
18
use Activation; 
19
20
use Fabrica\System\Eloquent\SysSetting;
21
use Fabrica\System\Eloquent\ResetPwdCode;
22
use Mail;
23
use Config;
24
25
class UserController extends Controller
26
{
27
    use ExcelTrait;
28
29
    public function __construct()
30
    {
31
        $this->middleware('privilege:sys_admin', [ 'except' => [ 'login', 'register', 'search', 'show', 'sendMailForResetpwd', 'showResetpwd', 'doResetpwd' ] ]);
32
        parent::__construct();
33
    }
34
35
    /**
36
     * user login.
37
     *
38
     * @return \Illuminate\Http\Response
39
     */
40
    public function login(Request $request)
41
    {
42
        $email = $request->input('email');
43
        $password = $request->input('password');
44
        if (!$email || !$password) {
45
            throw new \UnexpectedValueException('email or password cannot be empty.', -10003);
46
        }
47
48
        if (strpos($email, '@') === false) {
49
            $setting = SysSetting::first();
50 View Code Duplication
            if ($setting && isset($setting->properties) && isset($setting->properties['login_mail_domain'])) {
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...
51
                $email = $email . '@' . $setting->properties['login_mail_domain'];
52
            }
53
        }
54
55
        $user = Sentinel::authenticate([ 'email' => $email, 'password' => $password ]);
56 View Code Duplication
        if ($user) {
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...
57
            return response()->json([ 'ecode' => 0, 'data' => $user ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
58
        }
59
        else
60
        {
61
            return response()->json([ 'ecode' => -10000, 'data' => [] ]);
62
        }
63
    }
64
65
    /**
66
     * Display a listing of the resource.
67
     *
68
     * @return \Illuminate\Http\Response
69
     */
70
    public function search(Request $request)
71
    {
72
        $s = $request->input('s');
73
        $users = [];
74
        if ($s) {
75
            $search_users = EloquentUser::Where('first_name', 'like', '%' . $s .  '%')
76
                ->orWhere('email', 'like', '%' . $s .  '%')
77
                ->get([ 'first_name', 'last_name', 'email', 'invalid_flag' ]);
78
79
            $i = 0;
80
            foreach ($search_users as $key => $user)
81
            {
82
                if ((isset($user->invalid_flag) && $user->invalid_flag === 1) || Activation::completed($user) === false || $user->email === '[email protected]') {
83
                    continue;
84
                }
85
86
                $users[$i]['id'] = $user->id;
87
                $users[$i]['name'] = $user->first_name ?: '';
88
                $users[$i]['email'] = $user->email;
89
                if (++$i >= 10) {
90
                    break;
91
                }
92
            }
93
        }
94
        return response()->json([ 'ecode' => 0, 'data' => $users ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
95
    }
96
97
    /**
98
     * Display a listing of the resource.
99
     *
100
     * @return \Illuminate\Http\Response
101
     */
102
    public function index(Request $request)
103
    {
104
        $query = EloquentUser::where('email', '<>', '')->where('email', '<>', '[email protected]');
105
106
        if ($name = $request->input('name')) {
107
            $query->where(
108
                function ($query) use ($name) {
109
                    $query->where('email', 'like', '%' . $name . '%')->orWhere('name', 'like', '%' . $name . '%');
110
                }
111
            );
112
        }
113
114
        if ($group_id = $request->input('group')) {
115
            $group = Group::find($group_id);
116
            if ($group) {
117
                $query->whereIn('_id', $group->users ?: []);
118
            }
119
        }
120
121
        if ($directory = $request->input('directory')) {
122
            $query->where('directory', $directory);
123
        }
124
125
        // get total
126
        $total = $query->count();
127
128
        $query->orderBy('_id', 'asc');
129
130
        $page_size = 50;
131
        $page = $request->input('page') ?: 1;
132
        $query = $query->skip($page_size * ($page - 1))->take($page_size);
133
        $all_users = $query->get([ 'first_name', 'last_name', 'email', 'phone', 'directory', 'invalid_flag' ]);
134
135
        $users = [];
136
        foreach ($all_users as $user)
137
        {
138
            $tmp = [];
139
            $tmp['id'] = $user->id;
140
            $tmp['first_name'] = $user->first_name;
141
            $tmp['email'] = $user->email;
142
            $tmp['phone'] = $user->phone ?: '';
143
            $tmp['groups'] = array_column(Group::whereRaw([ 'users' => $user->id ])->get([ 'name' ])->toArray() ?: [], 'name');
144
            $tmp['directory'] = $user->directory ?: 'self';
145
            $tmp['status'] = $user->invalid_flag === 1 ? 'invalid' : (Activation::completed($user) ? 'active' : 'unactivated');
146
147
            $users[] = $tmp;
148
        }
149
        return response()->json([ 'ecode' => 0, 'data' => $users, 'options' => [ 'total' => $total, 'sizePerPage' => $page_size, 'groups' => Group::all(), 'directories' => Directory::all() ] ]); 
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
150
    }
151
152
    /**
153
     * Store a newly created resource in storage.
154
     *
155
     * @param  \Illuminate\Http\Request $request
156
     * @return \Illuminate\Http\Response
157
     */
158
    public function register(Request $request)
159
    {
160
        if (!($first_name = $request->input('first_name'))) {
161
            throw new \UnexpectedValueException('the name can not be empty.', -10100);
162
        }
163
164
        if (!($email = $request->input('email'))) {
165
            throw new \UnexpectedValueException('the email can not be empty.', -10101);
166
        }
167
168
        if (Sentinel::findByCredentials([ 'email' => $email ])) {
169
            throw new \InvalidArgumentException('the email has already been registered.', -10102);
170
        }
171
172
        if (!$password = $request->input('password')) {
173
            throw new \UnexpectedValueException('the password can not be empty.', -10103);
174
        }
175
176
        $user = Sentinel::register([ 'first_name' => $first_name, 'email' => $email, 'password' => $password ], true);
177
        return response()->json([ 'ecode' => 0, 'data' => $user ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
178
    }
179
180
    /**
181
     * Store a newly created resource in storage.
182
     *
183
     * @param  \Illuminate\Http\Request $request
184
     * @return \Illuminate\Http\Response
185
     */
186
    public function store(Request $request)
187
    {
188
        if (!($first_name = $request->input('first_name'))) {
189
            throw new \UnexpectedValueException('the name can not be empty.', -10100);
190
        }
191
192
        if (!($email = $request->input('email'))) {
193
            throw new \UnexpectedValueException('the email can not be empty.', -10101);
194
        }
195
196
        if (Sentinel::findByCredentials([ 'email' => $email ])) {
197
            throw new \InvalidArgumentException('email has already existed.', -10102);
198
        }
199
200
        $phone = $request->input('phone') ? $request->input('phone') : '';
201
202
        $user = Sentinel::register([ 'first_name' => $first_name, 'email' => $email, 'password' => 'actionview', 'phone' => $phone ], true);
203
        $user->status = Activation::completed($user) ? 'active' : 'unactivated';
204
205
        return response()->json([ 'ecode' => 0, 'data' => $user ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
206
    }
207
208
    /**
209
     * import the users.
210
     *
211
     * @param  \Illuminate\Http\Request $request
212
     * @return \Illuminate\Http\Response
213
     */
214
    public function imports(Request $request)
215
    {
216
        if (!($fid = $request->input('fid'))) {
217
            throw new \UnexpectedValueException('the user file ID can not be empty.', -11140);
218
        }
219
220
        $pattern = $request->input('pattern');
221
        if (!isset($pattern)) {
222
            $pattern = '1';
223
        }
224
225
        $file = config('filesystems.disks.local.root', '/tmp') . '/' . substr($fid, 0, 2) . '/' . $fid;
226
        if (!file_exists($file)) {
227
            throw new \UnexpectedValueException('the file cannot be found.', -11141);
228
        }
229
230
        Excel::load(
231
            $file, function ($reader) use ($pattern) {
232
                $reader = $reader->getSheet(0);
233
                $data = $reader->toArray();
234
235
                $fields = [ 'first_name' => '姓名', 'email' => '邮箱', 'phone' => '手机号' ];
236
                $data = $this->arrangeExcel($data, $fields);
237
238
                foreach ($data as $value) 
239
                {
240
                    if (!isset($value['first_name']) || !$value['first_name']) {
241
                        throw new \UnexpectedValueException('there is empty value in the name column', -10110);
242
                    }
243
244
                    if (!isset($value['email']) || !$value['email']) {
245
                        throw new \UnexpectedValueException('there is empty value in the email column', -10111);
246
                    }
247
                }
248
249
                foreach ($data as $value)
250
                {
251
                    $old_user = Sentinel::findByCredentials([ 'email' => $value['email'] ]);
252
                    if ($old_user) {
253
                        if ($pattern == '1') {
254
                            continue;
255
                        }
256
                        else
257
                        {
258
                            Sentinel::update($old_user, $value + [ 'password' => 'actionview' ]); 
259
                        }
260
261
                    }
262
                    else
263
                    {
264
                        Sentinel::register($value + [ 'password' => 'actionview' ], true);
265
                    }
266
                }
267
            }
268
        );
269
270
        return response()->json([ 'ecode' => 0, 'data' => [ 'ok' => true ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
271
    }
272
273
    /**
274
     * Display the specified resource.
275
     *
276
     * @param  int $id
277
     * @return \Illuminate\Http\Response
278
     */
279
    public function show(Request $request, $id)
280
    {
281
        return response()->json([ 'ecode' => 0, 'data' => Sentinel::findById($id) ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
282
    }
283
284
    /**
285
     * Update the specified resource in storage.
286
     *
287
     * @param  \Illuminate\Http\Request $request
288
     * @param  int                      $id
289
     * @return \Illuminate\Http\Response
290
     */
291
    public function update(Request $request, $id)
292
    {
293
        $first_name = $request->input('first_name');
294
        if (isset($first_name)) {
295
            if (!$first_name) {
296
                throw new \UnexpectedValueException('the name can not be empty.', -10100);
297
            }
298
        }
299
300
        $email = $request->input('email');
301 View Code Duplication
        if (isset($email)) {
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...
302
            if (!$email) {
303
                throw new \UnexpectedValueException('the email can not be empty.', -10101);
304
            }
305
            if ($user = Sentinel::findByCredentials([ 'email' => $email ])) {
306
                if ($user->id !== $id) {
307
                    throw new \InvalidArgumentException('email has already existed.', -10102);
308
                }
309
            }
310
        }
311
312
        $user = Sentinel::findById($id);
313
        if (!$user) {
314
            throw new \UnexpectedValueException('the user does not exist.', -10106);
315
        }
316
        if (isset($user->diectory) && $user->directory && $user->diectory != 'self') {
317
            throw new \UnexpectedValueException('the user come from external directroy.', -10109);
318
        }
319
320
        $valid = Sentinel::validForUpdate($user, array_only($request->all(), ['first_name', 'email', 'phone', 'invalid_flag']));
321
        if (!$valid) {
322
            throw new \UnexpectedValueException('updating the user does fails.', -10107);
323
        }
324
325
        $user = Sentinel::update($user, array_only($request->all(), ['first_name', 'email', 'phone', 'invalid_flag']));
326
        $user->status = $user->invalid_flag === 1 ? 'invalid' : (Activation::completed($user) ? 'active' : 'unactivated');
327
328
        $user->groups = array_column(Group::whereRaw([ 'users' => $user->id ])->get([ 'name' ])->toArray() ?: [], 'name');
329
330
        return response()->json([ 'ecode' => 0, 'data' => $user ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
331
    }
332
333
    /**
334
     * Remove the specified resource from storage.
335
     *
336
     * @param  int $id
337
     * @return \Illuminate\Http\Response
338
     */
339 View Code Duplication
    public function destroy($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
340
    {
341
        $user = Sentinel::findById($id);
342
        if (!$user) {
343
            throw new \UnexpectedValueException('the user does not exist.', -10106);
344
        }
345
        if (isset($user->diectory) && $user->directory && $user->diectory != 'self') {
346
            throw new \UnexpectedValueException('the user come from external directroy.', -10109);
347
        }
348
349
        $user->delete();
350
        Event::fire(new DelUserEvent($id));
351
        return response()->json([ 'ecode' => 0, 'data' => [ 'id' => $id ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
352
    }
353
354
    /**
355
     * delete all selected users.
356
     *
357
     * @return \Illuminate\Http\Response
358
     */
359 View Code Duplication
    public function delMultiUsers(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
360
    {
361
        $ids = $request->input('ids');
362
        if (!isset($ids) || !$ids) {
363
            throw new \InvalidArgumentException('the selected users cannot been empty.', -10108);
364
        }
365
366
        $deleted_ids = [];
367
        foreach ($ids as $id)
368
        {
369
            $user = Sentinel::findById($id);
370
            if ($user) {
371
                if (isset($user->directory) && $user->directory && $user->directory != 'self') {
372
                    continue;
373
                }
374
375
                $user->delete();
376
                Event::fire(new DelUserEvent($id));
377
                $deleted_ids[] = $id;
378
            }
379
        }
380
        return response()->json([ 'ecode' => 0, 'data' => [ 'ids' => $deleted_ids ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
381
    }
382
383
    /**
384
     * valid/invalid all selected users.
385
     *
386
     * @return \Illuminate\Http\Response
387
     */
388
    public function InvalidateMultiUsers(Request $request)
389
    {
390
        $ids = $request->input('ids');
391
        if (!isset($ids) || !$ids) {
392
            throw new \InvalidArgumentException('the selected users cannot been empty.', -10108);
393
        }
394
395
        $flag = $request->input('flag') ?: 1;
396
397
        $new_ids = [];
398
        foreach ($ids as $id)
399
        {
400
            $user = Sentinel::findById($id);
401
            if ($user) {
402
                if (isset($user->directory) && $user->directory && $user->directory != 'self') {
403
                    continue;
404
                }
405
                Sentinel::update($user, [ 'invalid_flag' => $flag ]);
406
                $new_ids[] = $id;
407
            }
408
        }
409
        return response()->json([ 'ecode' => 0, 'data' => [ 'ids' => $new_ids ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
410
    }
411
412
    /**
413
     * reset the user password.
414
     *
415
     * @param  \Illuminate\Http\Request $request
416
     * @param  int                      $id
417
     * @return \Illuminate\Http\Response
418
     */
419
    public function renewPwd(Request $request, $id)
420
    {
421
        $user = Sentinel::findById($id);
422
        if (!$user) {
423
            throw new \UnexpectedValueException('the user does not exist.', -10106);
424
        }
425
426
        $valid = Sentinel::validForUpdate($user, [ 'password' => 'actionview' ]);
427
        if (!$valid) {
428
            throw new \UnexpectedValueException('updating the user does fails.', -10107);
429
        }
430
431
        $user = Sentinel::update($user, [ 'password' => 'actionview' ]);
432
        return response()->json([ 'ecode' => 0, 'data' => $user ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
433
    }
434
435
    /**
436
     * send the reset password link to the mail.
437
     *
438
     * @param  \Illuminate\Http\Request $request
439
     * @return \Illuminate\Http\Response
440
     */
441
    public function sendMailForResetpwd(Request $request)
442
    {
443
        $email = $request->input('email');
444
        if (!isset($email) || !$email) {
445
            throw new \UnexpectedValueException('the email can not be empty.', -10019);
446
        }
447
448
        $obscured_email = $sendto_email = $email;
449
450
        $last_reset_times = ResetPwdCode::where('requested_at', '>=', time() - 10 * 60)->count();
451
        if ($last_reset_times >= 10) {
452
            throw new \UnexpectedValueException('sending the email is too often.', -10016);
453
        }
454
455
        $last_reset_times = ResetPwdCode::where('requested_at', '>=', time() - 10 * 60)->where('email', $email)->count();
456
        if ($last_reset_times >= 3) {
457
            throw new \UnexpectedValueException('sending the email is too often.', -10016);
458
        }
459
460
        $user = Sentinel::findByCredentials([ 'email' => $email ]);
461 View Code Duplication
        if (!$user) {
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...
462
            throw new \UnexpectedValueException('the user is not exists.', -10010);
463
        }
464
        else if ($user->invalid_flag === 1) {
465
            throw new \UnexpectedValueException('the user has been disabled.', -10011);
466
        }
467
        else if ($user->directory && $user->directory != 'self') {
468
            throw new \UnexpectedValueException('the user is external sync user.', -10012);
469
        }
470
471
        if ($email === '[email protected]') {
472
            if (isset($user->bind_email) && $user->bind_email) {
473
                $sendto_email = $user->bind_email;
474
                $sections = explode('@', $user->bind_email);
475
                $sections[0] = substr($sections[0], 0, 1) . '***' . substr($sections[0], -1, 1);
476
                $obscured_email = implode('@', $sections);
477
            }
478
            else
479
            {
480
                throw new \UnexpectedValueException('the related email is not bound.', -10013);
481
            }
482
        }
483
484
        $data = [];
485
        $data['email'] = $email;
486
        $rand_code = md5($email . mt_rand() . microtime());
487
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
488
        $data['url'] = $http_type . $_SERVER['HTTP_HOST'] . '/actionview/resetpwd?code=' . $rand_code;
489
490
        $this->sendMail($sendto_email, $data);
491
492
        ResetPwdCode::create(
493
            [
494
            'email' => $email,
495
            'code' => $rand_code,
496
            'requested_at' => time(),
497
            'expired_at' => time() + 24 * 60 * 60,
498
            ]
499
        );
500
501
        return response()->json([ 'ecode' => 0, 'data' => [ 'sendto_email' => $obscured_email ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
502
    }
503
504
    /**
505
     * send the reset link to the address.
506
     *
507
     * @param  string $to
508
     * @param  array  $data
509
     * @return \Illuminate\Http\Response
510
     */
511
    public function sendMail($to, $data)
512
    {
513
        $syssetting = SysSetting::first()->toArray();
514
        if (isset($syssetting['mailserver'])
515
            && isset($syssetting['mailserver']['send'])
516
            && isset($syssetting['mailserver']['smtp'])
517
            && isset($syssetting['mailserver']['send']['from'])
518
            && isset($syssetting['mailserver']['smtp']['host'])
519
            && isset($syssetting['mailserver']['smtp']['port'])
520
            && isset($syssetting['mailserver']['smtp']['username'])
521
            && isset($syssetting['mailserver']['smtp']['password'])
522
        ) {
523
            Config::set('mail.from', $syssetting['mailserver']['send']['from']);
524
            Config::set('mail.host', $syssetting['mailserver']['smtp']['host']);
525
            Config::set('mail.port', $syssetting['mailserver']['smtp']['port']);
526
            Config::set('mail.encryption', isset($syssetting['mailserver']['smtp']['encryption']) && $syssetting['mailserver']['smtp']['encryption'] ? $syssetting['mailserver']['smtp']['encryption'] : null);
527
            Config::set('mail.username', $syssetting['mailserver']['smtp']['username']);
528
            Config::set('mail.password', $syssetting['mailserver']['smtp']['password']);
529
        }
530
        else
531
        {
532
            throw new \UnexpectedValueException('the smtp server is not configured.', -10014);
533
        }
534
535
        $mail_prefix = 'ActionView';
536
        if (isset($syssetting['mailserver']['send']['prefix'])
537
            && $syssetting['mailserver']['send']['prefix']
538
        ) {
539
            $mail_prefix = $syssetting['mailserver']['send']['prefix'];
540
        }
541
542
        $subject = '[' . $mail_prefix . ']重置密码';
543
544
        try {
545
            Mail::send(
546
                'emails.resetpwdlink', $data, function ($message) use ($to, $subject) {
547
                    $message->from(Config::get('mail.from'), 'master')
548
                        ->to($to)
549
                        ->subject($subject);
550
                }
551
            );
552
        } catch (Exception $e){
0 ignored issues
show
Bug introduced by
The class Fabrica\Http\Api\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
553
            throw new Exception('send mail failed.', -15200);
554
        }
555
    }
556
557
    /**
558
     * show the reset password link.
559
     *
560
     * @param  \Illuminate\Http\Request $request
561
     * @return \Illuminate\Http\Response
562
     */
563
    public function showResetpwd(Request $request)
564
    {
565
        $code = $request->input('code');
566
        if (!isset($code) || !$code) {
567
            throw new \UnexpectedValueException('the link is not exists.', -10018);
568
        }
569
570
        $reset_code = ResetPwdCode::where('code', $code)->first();
571
        if (!$reset_code) {
572
            throw new \UnexpectedValueException('the link is not exists.', -10018);
573
        }
574
575 View Code Duplication
        if ($reset_code->invalid_flag == 1) {
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...
576
            throw new \UnexpectedValueException('the link has been invalid.', -10020);
577
        }
578
        else if ($reset_code->expired_at < time()) {
579
            throw new \UnexpectedValueException('the link has been expired.', -10017);
580
        }
581
582
        $email = $reset_code->email;
583
        $user = Sentinel::findByCredentials([ 'email' => $email ]);
584 View Code Duplication
        if (!$user) {
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...
585
            throw new \UnexpectedValueException('the user is not exists.', -10010);
586
        }
587
        else if ($user->invalid_flag === 1) {
588
            throw new \UnexpectedValueException('the user has been disabled.', -10011);
589
        }
590
        else if ($user->directory && $user->directory != 'self') {
591
            throw new \UnexpectedValueException('the user is external sync user.', -10012);
592
        }
593
594
        return response()->json([ 'ecode' => 0, 'data' => [ 'email' => $reset_code['email'] ] ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
595
    }
596
597
    /**
598
     * reset the password.
599
     *
600
     * @param  \Illuminate\Http\Request $request
601
     * @return \Illuminate\Http\Response
602
     */
603
    public function doResetpwd(Request $request)
604
    {
605
        $code = $request->input('code');
606
        if (!isset($code) || !$code) {
607
            throw new \UnexpectedValueException('the link is not exists.', -10018);
608
        }
609
610
        $password = $request->input('password');
611
        if (!isset($password) || !$password) {
612
            throw new \UnexpectedValueException('the password can not be empty.', -10103);
613
        }
614
615
        $reset_code = ResetPwdCode::where('code', $code)->first();
616
        if (!$reset_code) {
617
            throw new \UnexpectedValueException('the link is not exists.', -10018);
618
        }
619
620 View Code Duplication
        if ($reset_code->invalid_flag == 1) {
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...
621
            throw new \UnexpectedValueException('the link has been invalid.', -10020);
622
        }
623
        else if ($reset_code->expired_at < time()) {
624
            throw new \UnexpectedValueException('the link has been expired.', -10017);
625
        }
626
627
        $email = $reset_code->email;
628
        $user = Sentinel::findByCredentials([ 'email' => $email ]);
629 View Code Duplication
        if (!$user) {
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...
630
            throw new \UnexpectedValueException('the user is not exsits.', -10010);
631
        }
632
        else if ($user->invalid_flag === 1) {
633
            throw new \UnexpectedValueException('the user has been disabled.', -10011);
634
        }
635
        else if ($user->directory && $user->directory != 'self') {
636
            throw new \UnexpectedValueException('the user is external sync user.', -10012);
637
        }
638
639
        $valid = Sentinel::validForUpdate($user, [ 'password' => $password ]);
640
        if (!$valid) {
641
            throw new \UnexpectedValueException('updating the user does fails.', -10107);
642
        }
643
644
        $user = Sentinel::update($user, [ 'password' => $password ]);
645
646
        $reset_code->invalid_flag = 1;
647
        $reset_code->save();
648
        
649
        return response()->json([ 'ecode' => 0, 'data' => $user ]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
650
    }
651
652
    /**
653
     * Download user template file.
654
     *
655
     * @param \Illuminate\Http\Request $request
656
     */
657
    public function downloadUserTpl(Request $request)
658
    {
659
        $output = fopen('php://output', 'w') or die("can't open php://output");  
660
661
        header("Content-type:text/csv;charset=utf-8");
662
        header("Content-Disposition:attachment;filename=import-user-template.csv");
663
664
        fputcsv($output, [ 'name', 'email', 'phone' ]);  
665
        fputcsv($output, [ 'Tom', '[email protected]', '13811111111' ]);  
666
        fputcsv($output, [ 'Alice', '[email protected]', '13611111111' ]);  
667
        fclose($output) or die("can't close php://output"); 
668
        exit;
669
    }
670
}
671