UserController.php 13.3 KB
Newer Older
冯超鹏's avatar
冯超鹏 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/**
 * File UserController.php
 *
 * @author Tuan Duong <bacduong@gmail.com>
 * @package Laravue
 * @version 1.0
 */

namespace App\Http\Controllers;

use App\Http\Resources\PermissionResource;
use App\Http\Requests\UsersRequest;
use App\Http\Resources\UserResource;
use App\Laravue\JsonResponse;
use App\Laravue\Models\Permission;
use App\Laravue\Models\Role;
use App\Laravue\Models\User;
use App\Laravue\Models\Users;
use Illuminate\Http\Request;
冯超鹏's avatar
冯超鹏 committed
21
use Illuminate\Support\Facades\Auth;
冯超鹏's avatar
冯超鹏 committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Validator;

/**
 * Class UserController
 *
 * @package App\Http\Controllers
 */
class UserController extends Controller
{
    const ITEM_PER_PAGE = 15;

    /**
     * Display a listing of the user resource.
     *
冯超鹏's avatar
冯超鹏 committed
40
     * @param  \Illuminate\Http\Request $request
冯超鹏's avatar
冯超鹏 committed
41 42 43 44 45 46 47 48 49 50 51
     * @return \Illuminate\Http\Response|ResourceCollection
     */
    public function index(Request $request)
    {
        $searchParams = $request->all();
        $userQuery = User::query();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $role = Arr::get($searchParams, 'role', '');
        $keyword = Arr::get($searchParams, 'keyword', '');

        if (!empty($role)) {
冯超鹏's avatar
冯超鹏 committed
52 53 54
            $userQuery->whereHas('roles', function ($q) use ($role) {
                $q->where('name', $role);
            });
冯超鹏's avatar
冯超鹏 committed
55 56 57 58 59 60 61 62 63 64 65 66 67
        }

        if (!empty($keyword)) {
            $userQuery->where('name', 'LIKE', '%' . $keyword . '%');
            $userQuery->where('email', 'LIKE', '%' . $keyword . '%');
        }

        return UserResource::collection($userQuery->paginate($limit));
    }

    /**
     * Store a newly created resource in storage.
     *
冯超鹏's avatar
冯超鹏 committed
68
     * @param  \Illuminate\Http\Request $request
冯超鹏's avatar
冯超鹏 committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            array_merge(
                $this->getValidationRules(),
                [
                    'password' => ['required', 'min:6'],
                    'confirmPassword' => 'same:password',
                ]
            )
        );

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 403);
        } else {
            $params = $request->all();
            $user = User::create([
                'name' => $params['name'],
                'email' => $params['email'],
                'password' => Hash::make($params['password']),
            ]);
            $role = Role::findByName($params['role']);
            $user->syncRoles($role);

            return new UserResource($user);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  User $user
     * @return UserResource|\Illuminate\Http\JsonResponse
     */
    public function show(User $user)
    {
        return new UserResource($user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
冯超鹏's avatar
冯超鹏 committed
115
     * @param User $user
冯超鹏's avatar
冯超鹏 committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
     * @return UserResource|\Illuminate\Http\JsonResponse
     */
    public function update(Request $request, User $user)
    {
        if ($user === null) {
            return response()->json(['error' => 'User not found'], 404);
        }
        if ($user->isAdmin()) {
            return response()->json(['error' => 'Admin can not be modified'], 403);
        }

        $validator = Validator::make($request->all(), $this->getValidationRules(false));
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 403);
        } else {
            $email = $request->get('email');
            $found = User::where('email', $email)->first();
            if ($found && $found->id !== $user->id) {
                return response()->json(['error' => 'Email has been taken'], 403);
            }

            $user->name = $request->get('name');
            $user->email = $email;
            $user->save();
            return new UserResource($user);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
冯超鹏's avatar
冯超鹏 committed
148
     * @param User $user
冯超鹏's avatar
冯超鹏 committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162
     * @return UserResource|\Illuminate\Http\JsonResponse
     */
    public function updatePermissions(Request $request, User $user)
    {
        if ($user === null) {
            return response()->json(['error' => 'User not found'], 404);
        }

        if ($user->isAdmin()) {
            return response()->json(['error' => 'Admin can not be modified'], 403);
        }

        $permissionIds = $request->get('permissions', []);
        $rolePermissionIds = array_map(
冯超鹏's avatar
冯超鹏 committed
163
            function ($permission) {
冯超鹏's avatar
冯超鹏 committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
                return $permission['id'];
            },

            $user->getPermissionsViaRoles()->toArray()
        );

        $newPermissionIds = array_diff($permissionIds, $rolePermissionIds);
        $permissions = Permission::allowed()->whereIn('id', $newPermissionIds)->get();
        $user->syncPermissions($permissions);
        return new UserResource($user);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  User $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        if ($user->isAdmin()) {
            response()->json(['error' => 'Ehhh! Can not delete admin user'], 403);
        }

        try {
            $user->delete();
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }

        return response()->json(null, 204);
    }

    /**
     * Get permissions from role
     *
     * @param User $user
     * @return array|\Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function permissions(User $user)
    {
        try {
            return new JsonResponse([
                'user' => PermissionResource::collection($user->getDirectPermissions()),
                'role' => PermissionResource::collection($user->getPermissionsViaRoles()),
            ]);
        } catch (\Exception $ex) {
            response()->json(['error' => $ex->getMessage()], 403);
        }
    }

    /**
     * @param bool $isNew
     * @return array
     */
    private function getValidationRules($isNew = true)
    {
        return [
            'name' => 'required',
            'email' => $isNew ? 'required|email|unique:users' : 'required|email',
            'roles' => [
                'required',
                'array'
            ],
        ];
    }

冯超鹏's avatar
冯超鹏 committed
231 232 233 234 235 236 237 238 239 240 241 242
    /**
     * @param bool $isNew
     * @return array
     */
    private function getValidationRulescontacts($isNew = true)
    {
        return [
            'contacts_name' => 'required|max:3',
            'contacts_phone' => 'required|regex:/^1[3465789]\d{9}$/|max:11|unique:contactsuser,contacts_phone'
        ];
    }

冯超鹏's avatar
冯超鹏 committed
243 244 245 246 247 248 249 250 251
    /**
     * @param bool $isNew
     * @return array
     * 用户提交表单验证
     */
    private function getValidationRulesuser($isNew = true)
    {
        return [
            'email' => $isNew ? 'required|email|unique:users' : 'required|email',
冯超鹏's avatar
冯超鹏 committed
252 253 254
            'username' => 'required|between:2,25|regex:/^[A-Za-z0-9\-\_]+$/|unique:BackgroundUser,username',
            'password' => 'sometimes|required|string|min:6',
            'nickname' => 'required|between:2,25|regex:/^[A-Za-z0-9\-\_]+$/|unique:BackgroundUser,nickname'
冯超鹏's avatar
冯超鹏 committed
255 256 257
        ];
    }

冯超鹏's avatar
冯超鹏 committed
258
//    后台管理用户列表
冯超鹏's avatar
冯超鹏 committed
259 260 261
    public function HUserList(Request $request)
    {
        $pagenNum = $request->input('page') - 1;//页数
冯超鹏's avatar
冯超鹏 committed
262 263
        $limit = $request->input('limit');
        $users = DB::table('BackgroundUser as b')
冯超鹏's avatar
冯超鹏 committed
264
            ->where('b.state', '=', '2')
冯超鹏's avatar
冯超鹏 committed
265 266 267 268
            ->join('areachina as p', 'b.provinceid', '=', 'p.areaid')
            ->join('areachina as c', 'b.cityid', '=', 'c.areaid')
            ->join('areachina as a', 'b.areaid', '=', 'a.areaid')
            ->orderBy('b.id', 'desc')
冯超鹏's avatar
冯超鹏 committed
269
            ->select('b.username', 'b.nickname', 'b.email', 'b.state', 'a.area_name as area', 'c.area_name as city', 'p.area_name as province')
冯超鹏's avatar
冯超鹏 committed
270 271 272
            ->offset($pagenNum)
            ->limit($limit)
            ->get();
冯超鹏's avatar
冯超鹏 committed
273 274 275 276
        if ($users) {
            return $this->jsonSuccessData($users);
        } else {
            return $this->jsonErrorData(105, '获取失败');
冯超鹏's avatar
冯超鹏 committed
277 278
        }
    }
冯超鹏's avatar
冯超鹏 committed
279

冯超鹏's avatar
冯超鹏 committed
280
    //新增用户
冯超鹏's avatar
冯超鹏 committed
281 282
    public function addUser(Request $request)
    {
冯超鹏's avatar
冯超鹏 committed
283
        $userdata = $request->all();
冯超鹏's avatar
冯超鹏 committed
284
        //获取用户列表
冯超鹏's avatar
冯超鹏 committed
285
        $validator = Validator::make($request->all(), $this->getValidationRulesuser(false));
冯超鹏's avatar
冯超鹏 committed
286 287
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 403);
冯超鹏's avatar
冯超鹏 committed
288
        } else {
冯超鹏's avatar
冯超鹏 committed
289 290 291 292 293 294 295 296 297 298 299 300 301
            $type = new Users();
            $arr = $type->getTypeAllToArray($userdata);
            return $this->jsonSuccessData($arr);
        }
    }

    /*
     * 删除用户
     * type
     * 1 == 逻辑删除用户
     * 2  == 物理删除用户
     * duserid 删除用户的id
     * */
冯超鹏's avatar
冯超鹏 committed
302 303
    public function deleteuser(Request $request)
    {
冯超鹏's avatar
冯超鹏 committed
304
        $type = (int)$request->input('type');
冯超鹏's avatar
冯超鹏 committed
305 306 307
        $duserid = (int)$request->input('duserid');
        if ($type == '') {
            return $this->jsonErrorData(105, 'type参数不能为空');
冯超鹏's avatar
冯超鹏 committed
308
        }
冯超鹏's avatar
冯超鹏 committed
309 310
        if ($duserid == '') {
            return $this->jsonErrorData(105, 'duserid参数不能为空');
冯超鹏's avatar
冯超鹏 committed
311
        }
冯超鹏's avatar
冯超鹏 committed
312 313 314 315
        if ($type == 1) { // 逻辑删除
            $users = Users::where('id', '=', $duserid)
                ->update(['state' => 1]);
            if ($users) {
冯超鹏's avatar
冯超鹏 committed
316
                return $this->jsonSuccessData($users);
冯超鹏's avatar
冯超鹏 committed
317 318
            } else {
                return $this->jsonErrorData(105, '获取用户数据失败');
冯超鹏's avatar
冯超鹏 committed
319
            }
冯超鹏's avatar
冯超鹏 committed
320 321
        } else if ($type == 2) {
            $users = Users::where('id', '=', $duserid)
冯超鹏's avatar
冯超鹏 committed
322
                ->delete();
冯超鹏's avatar
冯超鹏 committed
323
            if ($users) {
冯超鹏's avatar
冯超鹏 committed
324
                return $this->jsonSuccessData($users);
冯超鹏's avatar
冯超鹏 committed
325 326
            } else {
                return $this->jsonErrorData(105, '获取用户数据失败');
冯超鹏's avatar
冯超鹏 committed
327 328 329
            }
        }
    }
冯超鹏's avatar
冯超鹏 committed
330

冯超鹏's avatar
冯超鹏 committed
331
    //更新用户
冯超鹏's avatar
冯超鹏 committed
332 333 334
    public function Upuser(Request $request)
    {
        if ($_POST) {
冯超鹏's avatar
冯超鹏 committed
335 336
            $userdata = $request->all();
            $uid = $userdata['userid'];
冯超鹏's avatar
冯超鹏 committed
337 338
            if (!isset($userdata['userid']) || $userdata['userid'] == '') {
                return $this->jsonErrorData(105, '用户id不能为空');
冯超鹏's avatar
冯超鹏 committed
339 340 341 342
            }
            $validator = Validator::make($request->all(), $this->getValidationRulesuser(false));
            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()], 403);
冯超鹏's avatar
冯超鹏 committed
343 344 345 346 347 348 349 350
            } else {
                foreach ($userdata as $k => $v) {
                    if ($k == 'userid') {
                        unset($userdata[$k]);
                    }
                }
                $re = Users::where('id', '=', (int)$uid)->update($userdata);
                if ($re) {
冯超鹏's avatar
冯超鹏 committed
351
                    return $this->jsonSuccessData($re);
冯超鹏's avatar
冯超鹏 committed
352 353
                } else {
                    return $this->jsonErrorData(105, '更新失败');
冯超鹏's avatar
冯超鹏 committed
354 355
                }
            }
冯超鹏's avatar
冯超鹏 committed
356
        } else {
冯超鹏's avatar
冯超鹏 committed
357
//            获取用户数据
冯超鹏's avatar
冯超鹏 committed
358 359 360
            $userid = (int)$request->input('userid');
            if ($userid == '') {
                return $this->jsonErrorData(105, '用户id不能为空');
冯超鹏's avatar
冯超鹏 committed
361
            }
冯超鹏's avatar
冯超鹏 committed
362 363 364 365 366
            $userdata = Users::where('id', '=', $userid)
                ->select('username', 'nickname', 'email', 'title', 'company', 'mapcenter')
                ->where('state', '=', 2)
                ->first();
            if ($userdata) {
冯超鹏's avatar
冯超鹏 committed
367
                return $this->jsonSuccessData($userdata);
冯超鹏's avatar
冯超鹏 committed
368 369
            } else {
                return $this->jsonErrorData(105, '获取数据失败');
冯超鹏's avatar
冯超鹏 committed
370
            }
冯超鹏's avatar
冯超鹏 committed
371 372
        }
    }
冯超鹏's avatar
冯超鹏 committed
373 374

    //返回地址列表
冯超鹏's avatar
冯超鹏 committed
375 376
    public function areachina(Request $request)
    {
冯超鹏's avatar
冯超鹏 committed
377
        $region = Db::table('areachina');
冯超鹏's avatar
冯超鹏 committed
378
        if ($_POST) {
冯超鹏's avatar
冯超鹏 committed
379
            $areaid = $request->input('areaid');
冯超鹏's avatar
冯超鹏 committed
380 381
            if ($areaid == '') {
                return $this->jsonErrorData('105', '地区id不能为空');
冯超鹏's avatar
冯超鹏 committed
382
            }
冯超鹏's avatar
冯超鹏 committed
383 384 385 386 387 388 389 390
            $area = $region->where('pid', '=', $areaid)
                ->where('status', '=', '1')
                ->select('area_name', 'areaid')
                ->get();
        } else {
            $area = $region->where('pid', '=', '0')
                ->where('status', '=', '1')
                ->select('area_name', 'areaid')
冯超鹏's avatar
冯超鹏 committed
391 392
                ->get();
        }
冯超鹏's avatar
冯超鹏 committed
393
        if ($area) {
冯超鹏's avatar
冯超鹏 committed
394
            return $this->jsonSuccessData($area);
冯超鹏's avatar
冯超鹏 committed
395 396
        } else {
            return $this->jsonErrorData(105, '获取失败');
冯超鹏's avatar
冯超鹏 committed
397 398 399
        }
    }

冯超鹏's avatar
冯超鹏 committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    //添加联系人
    public function addcontactsuser(Request $request)
    {
        $data = $request->all();
        if (!is_null($this->isadmin())) {//当前登入管理员
            $validator = Validator::make($request->all(), $this->getValidationRulescontacts(false));
            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()], 403);
            } else {
                $data['isadmin'] = 1;
            }
        } else {
            $data['isadmin'] = 2;
        }
        $data['contactsid'] = Auth::id();
        $isadmin = DB::table('contactsuser')->insert($data);
        return $this->jsonSuccessData($isadmin);
    }
   /*
    * 返回当前登入的联系人列表
    * */
    public  function contactslist(){
        return DB::table('contactsuser')->where([['contactsid','=',Auth::id()],['isadmin','=',is_null($this->isadmin()) ? '2' : '1']])->get();
    }
}