Bladeren bron

no message

panghu 1 jaar geleden
bovenliggende
commit
5fec9cf1b5

+ 1 - 1
.idea/php.xml

@@ -121,7 +121,7 @@
       <path value="$PROJECT_DIR$/vendor/psr/event-dispatcher" />
     </include_path>
   </component>
-  <component name="PhpProjectSharedConfiguration" php_language_level="8.0">
+  <component name="PhpProjectSharedConfiguration" php_language_level="7.3">
     <option name="suggestChangeDefaultLanguageLevel" value="false" />
   </component>
   <component name="PhpStanOptionsConfiguration">

+ 66 - 0
app/Http/Controllers/AdminApi/LoginController.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Http\Controllers\AdminApi;
+
+use App\Http\Controllers\FrontController;
+use App\Models\User;
+use App\Servers\PassServer;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Str;
+
+class LoginController extends FrontController
+{
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * 后台登录
+     * @return \Illuminate\Http\JsonResponse
+     */
+    function login(){
+        $phone = request()->input('phone', '13900139001');//账号
+        $password = request()->input('password', '123456');//密码
+        $code = request()->input('code', '');//验证码
+        if (empty($phone))  return $this->apiResponseError( '登录手机号必填');
+        if (empty($password))  return $this->apiResponseError( '登录密码必填');
+
+        $where = [['is_del',0], ['status',1], ['phone',$phone]];
+
+        $user = User::where($where)->select(['id', 'password', 'encrypt'])->first();
+        if (empty($user)) {
+            return $this->apiResponseError('当前账户不存在');
+        }
+        //密码验证
+        $pass_server = PassServer::creatServer($password, $user->{'encrypt'});
+        if (!$pass_server->verifyPass($user->{'password'})) {
+            return $this->apiResponseError('登陆密码错误');
+        }
+
+        $token = Str::random(60);
+        $api_token = hash('sha256', $token);
+
+        $token_ret = $user->update(['api_token'=>$api_token]);
+
+        if(empty($token_ret)){
+            return $this->apiResponseError('登陆信息更新失败');
+        }
+        //获取用户信息
+        $info = User::where('api_token', $api_token)->select(['id','name','email','phone'])->first();
+        return $this->apiResponseSuccess('登录成功',['token'=>$api_token,'user'=>$info]);
+    }
+
+
+    /**
+     * 退出登录
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function logout()
+    {
+        request()->session()->flush();
+
+        return $this->apiResponseSuccess('退出成功');
+    }
+}

+ 28 - 0
app/Http/Controllers/FrontController.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Http\Controllers\Traits\ApiResponseTrait;
+use Illuminate\Foundation\Bus\DispatchesJobs;
+use Illuminate\Foundation\Validation\ValidatesRequests;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+
+class FrontController extends Controller
+{
+    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
+    use ApiResponseTrait;
+
+    // 接口响应
+    /**
+     * 会员基本信息
+     * @var array
+     */
+    protected $member = null;
+
+    public function __construct()
+    {
+
+    }
+
+
+}

+ 61 - 0
app/Http/Controllers/Traits/ApiResponseTrait.php

@@ -0,0 +1,61 @@
+<?php
+
+
+namespace App\Http\Controllers\Traits;
+
+
+
+trait ApiResponseTrait
+{
+    /**
+     * @param array $data                       ## 返回数据
+     * @param string $msg                       ## 返回信息 如:auth.failed
+     * @param int $code                         ## 响应编码 1:成功 0:失败
+     * @param int $status                       ## HTTP响应状态 200:请求成功
+     * @param array $header                     ## 响应头
+     * @param int $options                      ## 其他信息
+     * @return \Illuminate\Http\JsonResponse
+     *
+     * 接口返回格式 | 成功
+     */
+    public function apiResponseSuccess( $msg = '',$data = [], $code = 1, $status = 200, $header = [], $options = 0)
+    {
+        $this->lang();
+        $msg=__($msg);
+        return response()->json([
+            'msg'   => $msg,
+            'data'  => empty($data) ? [] : $data,
+            'code'  => $code,
+        ], $status, $header, $options);
+    }
+
+    /**
+     * @param array $data                       ## 返回数据
+     * @param string $msg                       ## 返回信息 如:auth.failed
+     * @param int $code                         ## 响应编码 1:成功 0:失败
+     * @param int $status                       ## HTTP响应状态 200:请求成功
+     * @param array $header                     ## 响应头
+     * @param int $options                      ## 其他信息
+     * @return \Illuminate\Http\JsonResponse
+     *
+     * 接口返回格式 | 失败
+     */
+    public function apiResponseError( $msg = '',$data = [], $code = 0, $status = 200, $header = [], $options = 0)
+    {
+        $this->lang();
+        $msg=__($msg);
+        return response()->json([
+            'msg'   => $msg,
+            'data'  => empty($data) ? [] : $data,
+            'code'  => $code,
+        ], $status, $header, $options);
+    }
+
+    /**
+     * 双语设置
+     */
+    protected function lang()
+    {
+        app()->setLocale(request()->input('lang', 'zh'));
+    }
+}

+ 200 - 0
app/Http/Controllers/Traits/AuthUserTrait.php

@@ -0,0 +1,200 @@
+<?php
+
+namespace App\Http\Controllers\Traits;
+
+use Illuminate\Foundation\Auth\RedirectsUsers;
+use Illuminate\Foundation\Auth\ThrottlesLogins;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+
+trait AuthUserTrait
+{
+    use RedirectsUsers, ThrottlesLogins;
+
+    /**
+     * Show the application's login form.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function showLoginForm()
+    {
+        config()->set(['admin'=>['title'=>'后台登陆']]);
+        return view('auth.login');
+    }
+
+    /**
+     * Handle a login request to the application.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
+     */
+    public function login(Request $request)
+    {
+        $this->validateLogin($request);
+
+        // 验证码验证
+        $captcha = captcha_check($request->input('captcha'));
+
+        // 验证失败
+        if( !$captcha ){
+            return redirect()->back()
+                ->withInput($request->only($this->username(), 'remember'))
+                ->withErrors(['captcha'=>'验证错误']);
+        }
+
+        // If the class is using the ThrottlesLogins trait, we can automatically throttle
+        // the login attempts for this application. We'll key this by the username and
+        // the IP address of the client making these requests into this application.
+        if ($this->hasTooManyLoginAttempts($request)) {
+            $this->fireLockoutEvent($request);
+
+            return $this->sendLockoutResponse($request);
+        }
+
+        if ($this->attemptLogin($request)) {
+//            $request->setTrustedProxies(array('10.32.0.1/16'));
+//            $ip = $request->getClientIp();
+//            // 记录登录信息
+//            file_put_contents(
+//                storage_path('logs/auth-login.txt'),
+//                "登录时间:".(date('Y-m-d H:i:s'))." 登录IP:{$ip}"."\r\n", FILE_APPEND
+//            );
+            return $this->sendLoginResponse($request);
+        }
+
+        // If the login attempt was unsuccessful we will increment the number of attempts
+        // to login and redirect the user back to the login form. Of course, when this
+        // user surpasses their maximum number of attempts they will get locked out.
+        $this->incrementLoginAttempts($request);
+
+        return $this->sendFailedLoginResponse($request);
+    }
+
+    /**
+     * Validate the user login request.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return void
+     */
+    protected function validateLogin(Request $request)
+    {
+        $this->validate($request, [
+            $this->username() => 'required|string',
+            'password' => 'required|string',
+            'captcha' => 'required|string',
+        ],[
+            'required' => '必填'
+//            $this->username().'.required' => '必填',
+//            'password.required' => '必填',
+//            'captcha.required' => '必填'
+        ]);
+    }
+
+    /**
+     * Attempt to log the user into the application.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return bool
+     */
+    protected function attemptLogin(Request $request)
+    {
+        return $this->guard()->attempt(
+            $this->credentials($request), $request->has('remember')
+        );
+    }
+
+    /**
+     * Get the needed authorization credentials from the request.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return array
+     */
+    protected function credentials(Request $request)
+    {
+        return $request->only($this->username(), 'password');
+    }
+
+    /**
+     * Send the response after the user was authenticated.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\Response
+     */
+    protected function sendLoginResponse(Request $request)
+    {
+        $request->session()->regenerate();
+
+        $this->clearLoginAttempts($request);
+
+        return $this->authenticated($request, $this->guard()->user())
+            ?: redirect()->intended($this->redirectPath());
+    }
+
+    /**
+     * The user has been authenticated.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  mixed  $user
+     * @return mixed
+     */
+    protected function authenticated(Request $request, $user)
+    {
+        //
+    }
+
+    /**
+     * Get the failed login response instance.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\RedirectResponse
+     */
+    protected function sendFailedLoginResponse(Request $request)
+    {
+//        $errors = [$this->username() => trans('auth.failed')];
+        $errors = [$this->username() => '账号或密码错误'];;
+        if ($request->expectsJson()) {
+            return response()->json($errors, 422);
+        }
+
+        return redirect()->back()
+            ->withInput($request->only($this->username(), 'remember'))
+            ->withErrors($errors);
+    }
+
+    /**
+     * Get the login username to be used by the controller.
+     *
+     * @return string
+     */
+    public function username()
+    {
+        return 'email';
+    }
+
+    /**
+     * Log the user out of the application.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\Response
+     */
+    public function logout(Request $request)
+    {
+        $this->guard()->logout();
+
+        $request->session()->flush();
+
+        $request->session()->regenerate();
+
+        return redirect('/admin/login');
+    }
+
+    /**
+     * Get the guard to be used during authentication.
+     *
+     * @return \Illuminate\Contracts\Auth\StatefulGuard
+     */
+    protected function guard()
+    {
+        return Auth::guard();
+    }
+}

+ 39 - 0
app/Models/InviteCode.php

@@ -0,0 +1,39 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+use Prettus\Repository\Contracts\Transformable;
+use Prettus\Repository\Traits\TransformableTrait;
+
+/**
+ * Class InviteCode.
+ *
+ * @package namespace App\Models;
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode newModelQuery()
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode newQuery()
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode query()
+ * @mixin \Eloquent
+ * @property int $id
+ * @property int $code 编码
+ * @property int $status 状态
+ * @property \Illuminate\Support\Carbon|null $created_at
+ * @property \Illuminate\Support\Carbon|null $updated_at
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode whereCode($value)
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode whereCreatedAt($value)
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode whereId($value)
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode whereStatus($value)
+ * @method static \Illuminate\Database\Eloquent\Builder|InviteCode whereUpdatedAt($value)
+ */
+class InviteCode extends Model implements Transformable
+{
+    use TransformableTrait;
+
+    /**
+     * The attributes that are mass assignable.
+     *
+     * @var array
+     */
+    protected $guarded = ['id', 'updated_at', 'created_at'];
+
+}

+ 83 - 0
app/Servers/InviteCodeServer.php

@@ -0,0 +1,83 @@
+<?php
+
+
+namespace App\Servers;
+
+
+use App\Models\InviteCode;
+
+/**
+ * 图片OSS管理
+ */
+class InviteCodeServer
+{
+
+
+    static private $server = '';
+
+
+    private function __construct()
+    {
+
+    }
+
+    /**
+     * 创建对象
+     * @return InviteCodeServer
+     */
+    static function creatServer()
+    {
+        if (empty(self::$server)) {
+            self::$server = new  InviteCodeServer();
+        }
+        return self::$server;
+    }
+
+    /**
+     * 获取推荐码
+     * @return mixed
+     */
+    function getInviteCode()
+    {
+        $redis_on_name = 'invite_code_id' ;
+        $invite_code_id = RedisDataServer::creatServer()->getData($redis_on_name);
+        if(empty($invite_code_id)){
+            $invite_info = InviteCode::where('status', 0)->select(['id','code'])->first();
+            RedisDataServer::creatServer()->setData($redis_on_name,$invite_info->{'id'},'str',1800,false);
+        }else{
+            ++$invite_code_id;
+            RedisDataServer::creatServer()->setData($redis_on_name,$invite_code_id,'str',1800,false);
+            $invite_info = InviteCode::where('id','>',$invite_code_id)->where('status', 0)->select(['id','code'])->first();
+        }
+        $invite_info->update(['status'=>1]);
+        return $invite_info->{'code'};
+    }
+
+    /**
+     * 预生成编码
+     */
+    function setInviteCode()
+    {
+        if (file_exists(public_path('code/data-with-code-cache.json'))) {
+            $json = file_get_contents(public_path('code/data-with-code-cache.json'));
+            $json = json_decode($json, true);
+        } else {
+            $json = [];
+        }
+        for ($i = 1; $i <= 50000; ++$i) {
+            $invite_code = '';
+            $is_ok = true;
+            while ($is_ok) {
+                $invite_code = rand(10000000, 99999999);
+                if (!in_array($invite_code, $json)) {
+                    $is_ok = false;
+                    $json[] = $invite_code;
+                }
+            }
+            InviteCode::create(['code' => $invite_code, 'status' => 0]);
+        }
+        file_put_contents(public_path('code/data-with-code-cache.json'), json_encode($json));
+    }
+
+
+}

+ 157 - 0
app/Servers/PassServer.php

@@ -0,0 +1,157 @@
+<?php
+
+
+namespace App\Servers;
+
+
+/**
+ * Redis数据缓存类
+ */
+class PassServer
+{
+
+    /**
+     * 错误信息
+     * @var string
+     */
+    private $errorMsg = '';
+
+    private $password = '';
+
+
+    private function __construct($password = '', $encrypt = '')
+    {
+        $this->setPassword($password);
+        $this->setEncrypt($encrypt);
+    }
+
+    /**
+     * 创建对象
+     * @param string $password
+     * @param string $encrypt
+     * @return PassServer
+     */
+    static function creatServer($password = '', $encrypt = '')
+    {
+        return new PassServer($password, $encrypt);
+    }
+
+    /**
+     * @return string
+     */
+    public function getPassword(): string
+    {
+        return $this->password;
+    }
+
+    /**
+     * @param string $password
+     */
+    public function setPassword($password = ''): void
+    {
+        if (!empty($password)) $this->password = $password;
+    }
+
+    /**
+     * @return string
+     */
+    public function getEncrypt(): string
+    {
+        return $this->encrypt;
+    }
+
+    /**
+     * @param string $encrypt
+     */
+    public function setEncrypt($encrypt = ''): void
+    {
+        if (!empty($encrypt)) $this->encrypt = $encrypt;
+    }
+
+    private $encrypt = '';
+
+
+    /**
+     * @return string
+     */
+    public function getErrorMsg(): string
+    {
+        return $this->errorMsg;
+    }
+
+    /**
+     * 加密字符串
+     * @param $length
+     * @return null|string
+     */
+    public function getRandChar($length = 6)
+    {
+        $str = null;
+        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
+        $max = strlen($strPol) - 1;
+        for ($i = 0; $i < $length; $i++) {
+            $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
+        }
+        return $str;
+    }
+
+    /**
+     * 创建会员密码
+     * @return array|false
+     */
+    function creatPassword()
+    {
+        if (empty($this->password)) {
+            $this->errorMsg = "密码不能为空";
+            return false;
+        }
+        if (empty($this->encrypt)) $this->encrypt = $this->getRandChar();
+        $password = $this->memberPassword();
+        return ['password' => $password, 'encrypt' => $this->encrypt];
+    }
+
+    /**
+     * 验证密码
+     * @param $member_pass
+     * @return bool
+     */
+    public function verifyPass($member_pass)
+    {
+        $str = $this->memberPassword();
+        return $member_pass == $str;
+    }
+
+    /**
+     * 密码加密
+     * @return string
+     */
+     function memberPassword()
+    {
+        $str = md5($this->password) . md5($this->encrypt);
+        return md5($str);
+    }
+
+    /**
+     * 获取推荐码
+     * @return int|string
+     */
+    public function getInviteCode()
+    {
+        return InviteCodeServer::creatServer()->getInviteCode();
+    }
+
+
+
+    /**
+     * 生成会员登录token
+     * @param $m_id
+     * @return string
+     */
+    public function getMemberToken($m_id)
+    {
+        $token = md5($m_id . 'token' . time());
+        return $token;
+    }
+
+
+}

+ 232 - 0
app/Servers/RedisDataServer.php

@@ -0,0 +1,232 @@
+<?php
+
+
+namespace App\Servers;
+
+use Illuminate\Support\Facades\Redis;
+
+
+/**
+ * Redis数据缓存类
+ */
+class RedisDataServer
+{
+    /**
+     * 单列对象
+     * @var
+     */
+    private static $server;
+
+    private function __construct()
+    {
+
+    }
+
+    /**
+     * 创建对象
+     * @return RedisDataServer
+     */
+    static function creatServer()
+    {
+        if (empty(self::$server)) {
+            self::$server = new RedisDataServer();
+        }
+        return self::$server;
+    }
+
+    /**
+     * 获取缓存数据
+     * @param $key
+     * @param string $type
+     * @return mixed
+     */
+    function getData($key, $type = 'str')
+    {
+       
+        $value = Redis::get($key);
+        if ($type == 'json') {
+            $value = json_decode($value, true);
+        }
+        return $value;
+    }
+
+    /**
+     * 设置缓存数据
+     * @param $key
+     * @param $value
+     * @param string $type
+     * @param int $time
+     * @param $random
+     */
+    function setData($key, $value, $type = 'str', $time = 10, $random = true)
+    {
+        if (!empty($value)) {
+            if ($type == 'json') {
+                $value = json_encode($value);
+            }
+            if ($time > 1 && $random) $time += $this->getRandom();
+            Redis::setex($key, $time, $value);
+        }
+
+    }
+
+    /**
+     * 长时间存放数据
+     * @param $key
+     * @param $value
+     * @param string $type
+     */
+    function setLongData($key, $value, $type = 'str')
+    {
+        if (!empty($value)) {
+            if ($type == 'json') {
+                $value = json_encode($value);
+            }
+            Redis::set($key, $value);
+        }
+
+    }
+
+    /**
+     * 更新数据
+     * @param $key
+     * @param $value
+     * @param string $type
+     * @param int $start_num
+     */
+    function setSetrange($key, $value, $type = 'str', $start_num = 0)
+    {
+        if (!empty($value)) {
+            if ($type == 'json') {
+                $value = json_encode($value);
+            }
+            Redis::setrange($key, $start_num, $value);
+        }
+    }
+
+    /**
+     * 删除Redis数据
+     * @param $key
+     */
+    function delData($key)
+    {
+        Redis::del($key);
+    }
+
+    /**
+     * 获取随机数
+     * @return int
+     */
+    private function getRandom()
+    {
+        return mt_rand(1, 10);
+    }
+
+    /**
+     * 创建队列序号
+     * @param $key
+     * @param $num
+     * @return mixed
+     */
+    function setQueue($key, $num)
+    {
+        $num_arr = range(1, $num);
+        $key_num = Redis::lpush($key, $num_arr);
+        return $key_num;
+    }
+
+    /**
+     * 添加序号
+     * @param $key
+     * @param $num
+     * @return mixed
+     */
+    function addQueue($key, $num)
+    {
+        $key_num = Redis::lpush($key, $num);
+        return $key_num;
+    }
+
+    /**
+     * 弹出队列数据
+     * @param $key
+     * @return false
+     */
+    function getQueue($key)
+    {
+        $key_num = Redis::rpop($key);
+        if (empty($key_num)) $key_num = false;
+        return $key_num;
+    }
+
+    /**
+     * 队列阻塞弹出
+     * @param $key
+     * @param int $wait_time
+     * @return false
+     */
+    function getWaitQueue($key, $wait_time = 5)
+    {
+        $key_num = Redis::brpop($key, $wait_time);
+        if (empty($key_num)) $key_num = false;
+        return $key_num;
+    }
+
+    /**
+     * 获取队列数据长度
+     * @param $key
+     * @return mixed
+     */
+    function getQueueList($key)
+    {
+        $key_num = Redis::llen($key);
+        return $key_num;
+    }
+
+    /**
+     * 获取过期时间
+     * @param $key
+     * @return mixed
+     */
+    function getTime($key)
+    {
+        $key_num = Redis::ttl($key);
+        return $key_num;
+    }
+
+    /**
+     * 缓存清除
+     * @return mixed
+     */
+    function flushdb()
+    {
+        return Redis::flushdb();
+    }
+
+
+    /**
+     * key加锁
+     * @param $key
+     * @param $value
+     * @param int $time
+     * @return mixed
+     */
+    function lockKey($key,$value,$time = 10){
+        return Redis::set($key, $value, 'ex', $time, 'nx');
+    }
+
+    /**
+     * 解锁
+     * @param $key
+     * @param $value
+     * @return mixed
+     */
+    function unLockKey($key, $value)
+    {
+        $res = $this->getData($key);
+
+        if ($res == $value) {
+            return Redis::del($key);
+        }
+    }
+}

+ 12 - 0
routes/adminApi/auth.php

@@ -0,0 +1,12 @@
+<?php
+
+use Illuminate\Support\Facades\Route;
+
+
+Route::group( ['domain' => env('APP_HOST'), 'prefix' => 'adminApi'],function($router){
+
+    Route::match(['get','post'],'login', 'LoginController@login')->name('adminApi.login');// 登录
+    Route::match(['get','post'],'logout', 'LoginController@logout')->name('adminApi.logout');//退出
+});
+
+