Commit 623243e9 authored by yinxiaoling's avatar yinxiaoling

denglujiek

parent e1102d24
...@@ -7,7 +7,7 @@ APP_URL=http://localhost ...@@ -7,7 +7,7 @@ APP_URL=http://localhost
LOG_CHANNEL=stack LOG_CHANNEL=stack
DB_CONNECTION=pgsql DB_CONNECTION=pgsql
DB_HOST=127.0.0.1 DB_HOST=120.77.61.117
DB_PORT=5432 DB_PORT=5432
DB_DATABASE=postgres DB_DATABASE=postgres
DB_USERNAME=postgres DB_USERNAME=postgres
......
...@@ -4,9 +4,14 @@ namespace App\Http\Controllers\Auth; ...@@ -4,9 +4,14 @@ namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Tool;
use App\Http\Controllers\BaseController;
class LoginController extends Controller class LoginController extends BaseController
{ {
use Tool;
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Login Controller | Login Controller
...@@ -36,4 +41,37 @@ class LoginController extends Controller ...@@ -36,4 +41,37 @@ class LoginController extends Controller
{ {
$this->middleware('guest')->except('logout'); $this->middleware('guest')->except('logout');
} }
public function login(Request $request)
{
// 1. 获取前端发来的用户名和密码
$username = $request->input('username');
$password = $request->input('password');
$username = 'ljs';
$password = '123456';
$defaultuser = 'ljs'; //固定一个账号登录
if ($username != $defaultuser){
return $this->errorWithInfo('您的账号不允许登录', 401);
}
//调用小a登录接口
$url = "https://test117.ciopaas.com/api/login";
$params = ['username'=>$username,'password'=>$password,'from'=>"2"];
$params['url'] = substr(md5(json_encode($params)),1,8);
$requestReturn = $this->requestPost($url,$params);
//dump($requestReturn);
$requestReturnArr = json_decode($requestReturn,true);
if (isset($requestReturnArr['code'])){ //登录成功
if ($requestReturnArr['code'] == 0){
return $this->successWithInfo($requestReturnArr['data']);
}else{
return $this->errorWithInfo($requestReturnArr['msg'], 401);
}
}else{
return $this->errorWithInfo('登录接口异常', 401);
}
}
} }
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Rap2hpoutre\FastExcel\FastExcel;
use Illuminate\Support\Facades\Validator;
/**
* @SWG\Swagger(
* basePath="/calculate-rates",
* @SWG\Info(
* title="项目名称 API",
* version="1.0.0"
* )
* )
*/
class BaseController extends Controller
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
use Tool;
protected $model = ''; // 当前模型
protected $fillable = []; // 当前模型可以修改和新增的字段
protected $resource = ''; // 显示个体资源
protected $resourceCollection = ''; // 显示资源集合
protected $map = []; // 导入导出时候 数据表字段与说明的映射表
public function index(Request $request)
{
// 显示订单列表
$pageSize = $request->input('pageSize', 10);
$this->log('select', '显示信息列表');
return $this->getListData($pageSize);
}
protected function getListData($pageSize)
{
// 当前列表数据 对应于原来的index
$data = $this->model::paginate($pageSize);
return new $this->resourceCollection($data);
}
public function show($id)
{
$data = $this->model::find($id);
$this->log('select', '显示信息');
return new $this->resource($data);
}
public function store(Request $request)
{
// 1. 获取前端数据
$data = $request->only($this->fillable);
// 2. 验证数据
if (method_exists($this, 'message')) {
$validator = Validator::make($data, $this->storeRule(), $this->message());
} else {
$validator = Validator::make($data, $this->storeRule());
}
if ($validator->fails()) {
// 有错误,处理错误信息并且返回
$errors = $validator->errors();
$errorTips = '';
foreach ($errors->all() as $message) {
$errorTips = $errorTips.$message.',';
}
$errorTips = substr($errorTips, 0, strlen($errorTips)-1);
return $this->errorWithInfo($errorTips, 422);
}
// 3.数据无误,进一步处理后保存到数据表里面,有的表需要处理,有的不需要
$data = $this->storeHandle($data);
if ($this->model::create($data)) {
$this->log('insert', '新增信息');
return $this->successWithInfo('新增数据成功', 201);
} else {
return $this->error();
}
}
protected function storeHandle($data)
{
return $data; // TODO: Change the autogenerated stub
}
public function update(Request $request, $id)
{
$data = $request->only($this->fillable);
if (method_exists($this, 'message')) {
$validator = Validator::make($data, $this->updateRule($id), $this->message());
} else {
$validator = Validator::make($data, $this->updateRule($id));
}
if ($validator->fails()) {
// 有错误,处理错误信息并且返回
$errors = $validator->errors();
$errorTips = '';
foreach ($errors->all() as $message) {
$errorTips = $errorTips.$message.',';
}
$errorTips = substr($errorTips, 0, strlen($errorTips)-1);
return $this->errorWithInfo($errorTips, 422);
}
// 进一步处理数据
$data = $this->updateHandle($data);
// 更新到数据表
if ($this->model::where('id', $id)->update($data)) {
$this->log('update', '更新信息');
return $this->successWithInfo('数据更新成功');
} else {
return $this->errorWithInfo('数据更新失败');
}
}
protected function updateHandle($data)
{
return $data;
}
public function destroy($id)
{
if ($this->destoryHandle($id)) {
$this->log('delete', '删除信息');
return $this->successWithInfo('数据删除成功', 204);
} else {
return $this->errorWithInfo('数据删除失败,请查看指定的数据是否存在');
}
}
protected function destoryHandle($id)
{
DB::transaction(function () use ($id) {
// 删除逻辑 注意多表关联的情况
$this->model::where('id', $id)->delete();
});
return true;
}
public function deleteAll()
{
// 前端利用json格式传递数据
$ids = json_decode(request()->input('ids'), true);
foreach ($ids as $id) {
$this->destoryHandle($id);
}
$this->log('delete', '删除多条信息');
return $this->successWithInfo('批量删除数据成功', 204);
}
public function export()
{
$data = $this->model::all();
$data = $data->toArray();
$arr = $this->exportHandle($data);
$data = collect($arr);
$fileName = date('YmdHiS') . uniqid() .'.xlsx';
$file = 'xls\\'.$fileName;
(new FastExcel($data))->export($file);
$this->log('export', '导出信息');
return $this->successWithInfo($file);
}
protected function exportHandle($arrData)
{
// 默认会根据$map进行处理,
$arr = [];
foreach ($arrData as $item) {
$tempArr = $this->handleItem($item, 'export');
// 根据需要$tempArr可以进一步处理,特殊的内容,默认$tempArr是根据$this->map来处理
$arr[] = $tempArr;
}
return $arr;
}
/**
* 根据map表,处理数据
* @param $data
*/
protected function handleItem($data, $type = 'export')
{
$arr = [];
if ($type === 'export') {
foreach ($this->map as $key => $item) {
if (!isset($data[$item])) {
continue;
}
$arr[$key] = $data[$item];
}
}
if ($type === 'import') {
foreach ($this->map as $key => $item) {
if (!isset($data[$key])) {
continue;
}
$arr[$item] = $data[$key];
}
}
return $arr;
}
public function import()
{
// 1.接收文件,打开数据
// 2. 处理打开的数据,循环转换
// 3. 导入到数据库
$data = (new FastExcel())->import(request()->file('file'));
$arrData = $data->toArray();
$arr = $this->importHandle($arrData);
$this->model::insert($arr['successData']);
$tips = '当前操作导入数据成功'.$arr['successCount'].'条';
if ($arr['isError']) {
// 有失败的数据,无法插入,要显示出来,让前端能下载
$file = date('YmdHiS') . uniqid() .'.xlsx';
$fileName = public_path('xls').'\\'.$file;
$file = 'xls\\'.$file;
$data = collect($arr['errorData']);
(new FastExcel($data))->export($fileName);
$tips .= ',失败'.$arr['errorCount'].'条';
if ($arrData['successCount'] > 0) {
$this->log('import', '导入信息');
}
return response()->json([
'info' => $tips,
'fileName' => $file,
'status' => 'error',
'status_code' => 422
], 422);
} else {
$this->log('import', '导入信息');
return $this->successWithInfo($tips, 201);
}
}
protected function validatorData($item, $data, &$error, &$isError, &$successCount, &$errorCount, &$arr)
{
if (method_exists($this, 'message')) {
$validator = Validator::make($data, $this->storeRule(), $this->message());
} else {
$validator = Validator::make($data, $this->storeRule());
}
if ($validator->fails()) {
// 获取相关的错误信息,并且把错误信息单独存放
$errors = $validator->errors($validator);
$tips = '';
foreach ($errors->all() as $message) {
$tips .= $message.',';
}
$tips = substr($tips, 0, strlen($tips)-1);
// 状态信息
$item['错误原因'] = $tips;
$error[] = $item;
$isError = true;
$errorCount ++;
} else {
// 没有出错的,我们先存在正确的数组
$arr[] = $data;
$successCount ++;
}
}
protected function storeRule()
{
return [];
}
protected function UpdateRule($id)
{
return [];
}
protected function message(){
return [];
}
}
...@@ -4,7 +4,7 @@ namespace App\Http\Controllers; ...@@ -4,7 +4,7 @@ namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
class HomeController extends Controller class HomeController extends BaseController
{ {
/** /**
* Create a new controller instance. * Create a new controller instance.
...@@ -13,7 +13,7 @@ class HomeController extends Controller ...@@ -13,7 +13,7 @@ class HomeController extends Controller
*/ */
public function __construct() public function __construct()
{ {
$this->middleware('auth'); //$this->middleware('auth');
} }
/** /**
...@@ -21,8 +21,21 @@ class HomeController extends Controller ...@@ -21,8 +21,21 @@ class HomeController extends Controller
* *
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
public function index(){ public function index(Request $request){
//dd('首页'); //dd('首页');
//调用小a登录接口
$username = 'ljs';
$password = '123456';
$url = "https://test117.ciopaas.com/api/login";
$params = ['username'=>$username,'password'=>$password,'from'=>'2'];
$mdUrl = substr(md5(json_encode($params)),1,8);
$params['url'] = $mdUrl;
$returnData = $this->requestPost($url,$params);
dump($mdUrl);
dd($returnData);
return view('home'); return view('home');
} }
......
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\models\users;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\BaseController;
use App\User;
use Illuminate\Support\Facades\DB;
class LoginApiController extends BaseController
{
public function index(Request $request){
$param = $request->except('url');
$url = $request->url;
Log::channel('api')->info(substr(md5(json_encode($param)),1,8));
Log::channel('api')->info($url);
if($url != substr(md5(json_encode($param)),1,8)){
return $this->errorWithInfo('url验证不通过', 401);
}
if(empty($param['username']) || empty($param['password'] )|| empty($param['from'] ) || $param['from'] != 2){
return $this->errorWithInfo('参数验证不通过', 401);
}
$user = DB::table('users')->select('status','user_name','password','user_sn','team_name','password','expired','ai_count','caller_group','api_key','parent_sn')->where('user_name',$param['username'])
->where(function($query){
$query->where('status',0)->orWhere(function($query){
$query->whereNull('status');
});
})
->first();
if(empty($user)){
return $this->errorWithInfo('您的账号不存在', 401);
}
if($user->status == 1){
return $this->errorWithInfo('您的账号已被清理,请联系管理员处理', 401);
}
if(empty($user->parent_sn)){
$the_expired = $user->expired;
}else{
$puser = DB::table('users')->where('user_name',$user->parent_sn)->select('expired')->first();
$the_expired = $puser->expired;
}
$todayDate = strtotime(date('y-m-d 00:00:00',time()));
$expiredDate = strtotime($the_expired.' 00:00:00');
if(empty($the_expired) || $expiredDate - $todayDate <= 0){
return $this->errorWithInfo('您的账号已过期,请联系管理员处理', 401);
}
if(empty($user) || !password_verify($param['password'],$user->password)){
return $this->errorWithInfo('用户名或密码错误', 401);
}
//生成api_key
$api_key = $this->create_apikey(8);
$expire = time()+3600*10; //有效时间10小时
$data['api_key'] = $api_key;
$data['api_key_expire'] = $expire;
$rs = DB::table('users')->where('user_sn',$user->user_sn)->update($data);
$user->api_key = $api_key;
$user->api_key_expire = $expire;
unset($user->password);
if($rs){
return $this->successWithInfo(['data'=>(array)$user]);
}else{
return $this->errorWithInfo('登录失败', 401);
}
}
private function create_apikey( $length = 8 ) {
// 密码字符集,可任意添加你需要的字符
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = '';
for ( $i = 0; $i < $length; $i++ )
{
$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $password;
}
}
<?php
namespace App\Http\Controllers;
/* use App\Events\DataOperation;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route; */
trait Tool
{
public function success()
{
return response()->json(
[
'status' => 'success',
'status_code' => 200
]
,200);
}
public function successWithInfo($info, $code = 200)
{
return response()->json(
[
'info' => $info,
'status' => 'success',
'status_code' => $code
]
,$code);
}
public function successWithData($data)
{
return response()->json([
'data' => $data,
'status' => 'success',
'status_code' => 200
], 200);
}
public function error()
{
return response()->json(
[
'status' => 'error',
'status_code' => 404
]
,404);
}
public function errorWithInfo($info, $http_code = 404,$msg_code='')
{
return response()->json(
[
'info' => $info,
'status' => 'error',
'status_code' => $http_code,
'msg_code' => $msg_code?$msg_code:$http_code
] ,$http_code);
}
/* public function log($type, $desc)
{
$route_name = Route::currentRouteName();
$data = [
'type' => $type,
'route_name' => $route_name,
'desc' => $desc
];
event(new DataOperation($data));
} */
/* public function isAdmin()
{
$roles = explode(',', Auth::user()->roles);
return in_array('admin', $roles);
} */
/**
* 模拟post进行url请求
* @param string $url
* @param string $param
*/
public function requestPost($url = '', $post_data = array(),$header=array()) {
if (empty($url) || empty($post_data)) {
return false;
}
$o = "";
if(is_array($post_data) && count($post_data)){
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
}
$postUrl = $url;
$curlPost = $post_data;
$ch = curl_init();//初始化curl
if(!empty($header)){
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
return $data;
}
}
\ No newline at end of file
...@@ -60,6 +60,7 @@ class Kernel extends HttpKernel ...@@ -60,6 +60,7 @@ class Kernel extends HttpKernel
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'check.apikey' => \App\Http\Middleware\CheckApiKey::class,
]; ];
/** /**
......
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\models\users;
use Illuminate\Support\Facades\Log;
use App\User;
class CheckApiKey
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
$url=$request->url;
$param = $request->except(['url','client_info_json','source','aes','upload','fail_recall_of_reason']);
Log::channel('api')->info('API_PARAM:'.json_encode($param));
Log::channel('api')->info('API_SERVER_PARAM:'.substr(md5(json_encode($param)),1,8));
Log::channel('api')->info('API_CLIENT_PARAM:'.$url);
$md_url = substr(md5(json_encode($param)),1,8);
if(strcmp($url,$md_url)){
if($_SERVER['REQUEST_SCHEME'] == 'http'){
return response()->json(array('code'=> 10001,'msg'=>'验证url失败'));
}
}
$api_key=$request->api_key;
$user_sn=$request->user_sn;
$user = Users::where('user_sn',$param['user_sn'])->first();
if(empty($user->parent_sn)){
$the_expired = $user->expired;
}else{
$puser = Users::where('user_name',$user->parent_sn)->select('expired')->first();
$the_expired = $puser->expired;
}
$todayDate = strtotime(date('y-m-d 00:00:00',time()));
$expiredDate =strtotime($the_expired. ' 00:00:00');
if(empty($the_expired) || $expiredDate - $todayDate <= 0){
return response()->json(array('code'=> 20008,'msg'=>'您的账号已过期,请联系管理员处理'));
}
$request->attributes->add(['user'=>$user]);//添加参数
}catch (\Exception $e){
Log::info($e->getFile().'-'.$e->getLine().'-'.$e->getMessage());
return response()->json(array('code'=> 500,'msg'=>$e->getMessage().'-'.$e->getLine()));
}
return $next($request);
}
}
...@@ -34,6 +34,33 @@ return [ ...@@ -34,6 +34,33 @@ return [
*/ */
'channels' => [ 'channels' => [
//异步导入任务
'task' => [
// 日志驱动模式:
'driver' => 'daily',
// 日志存放路径
'path' => storage_path('logs/job/task.log'),
// 日志等级:
'level' => 'info',
// 日志分片周期,多少天一个文件
'days' => 7,
//日志文件权限
'permission' => 0666,
],
//接口记录
'api' => [
// 日志驱动模式:
'driver' => 'daily',
// 日志存放路径
'path' => storage_path('logs/api.log'),
// 日志等级:
'level' => 'info',
// 日志分片周期,多少天一个文件
'days' => 7,
//日志文件权限
'permission' => 0666,
],
'stack' => [ 'stack' => [
'driver' => 'stack', 'driver' => 'stack',
'channels' => ['daily'], 'channels' => ['daily'],
......
<?php <?php
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
class DatabaseSeeder extends Seeder class DatabaseSeeder extends Seeder
{ {
...@@ -12,5 +14,81 @@ class DatabaseSeeder extends Seeder ...@@ -12,5 +14,81 @@ class DatabaseSeeder extends Seeder
public function run() public function run()
{ {
// $this->call(UsersTableSeeder::class); // $this->call(UsersTableSeeder::class);
$tableName = 'strategy_set';//策略设置表
if(!Schema::hasTable($tableName)){
//创建表语句
Schema::create($tableName, function (Blueprint $table){
$table->increments('id');
$table->string('strategy_sn'); //sn编号
$table->string('strategy_name'); //策略名称
$table->string('user_sn'); //用户sn
$table->string('user_name'); //用户名
$table->string('parent_sn'); //主账号名
$table->string('project_sn'); //项目sn
$table->integer('day_type')->default(0); //外呼日期类型 0每天 1日期前一天和当天
$table->integer('frequency_type')->default(1);//外呼频率类型 (1 一天一次 2 一天两次)
$table->string('call_time_set'); //呼叫设置时间点,两个用#号分割
$table->integer('disabled')->default(1);//是否不可用 0启用 1停用
$table->integer('total')->default(0);//excel导入号码总数量
$table->integer('latest_total')->default(0);//最新一次导入excel号码数量
$table->timestamp('created_at')->nullable();
});
//加索引
Schema::table('seating_assistance_project_set', function ($table){
$table->index('strategy_sn');
$table->index('disabled');
});
//加注释
//$sql = "COMMENT ON COLUMN \"public\".\"seating_assistance_project_set\".\"is_seating_sensitive_word\" IS '是否坐席敏感词 0否 1是'";
//DB::statement($sql);
}
$tableName = 'strategy_excel';//策略excel数据记录表
if(!Schema::hasTable($tableName)){
//创建表语句
Schema::create($tableName, function (Blueprint $table){
$table->increments('id');
$table->string('strategy_sn'); //sn编号
$table->string('name'); //姓名
$table->string('duty_date')->nullable(); //值班日期
$table->integer('phone'); //手机号
$table->timestamp('created_at')->nullable();
});
//加索引
Schema::table('seating_assistance_project_set', function ($table){
$table->index('strategy_sn');
});
}
$tableName = 'task_data';//任务数据(任务已建未建)
if(!Schema::hasTable($tableName)){
//创建表语句
Schema::create($tableName, function (Blueprint $table){
$table->increments('id');
$table->string('name'); //sn编号
$table->string('duty_date')->nullable(); //值班日期(年月日)
$table->integer('phone'); //手机号
$table->string('call_date'); //外呼时间(年月日)
$table->string('call_time'); //外呼时间(时分秒)
$table->string('parent_sn'); //主账号名
$table->string('project_sn'); //项目sn
$table->integer('is_created')->default(0);//是否新建任务(0未建 1已建)
$table->integer('created_fail_number')->default(0);//任务创建失败尝试次数
$table->timestamp('created_at')->nullable();
});
//加索引
Schema::table('seating_assistance_project_set', function ($table){
$table->index('is_created');
$table->index('phone');
});
}
} }
} }
...@@ -16,3 +16,13 @@ use Illuminate\Http\Request; ...@@ -16,3 +16,13 @@ use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) { Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user(); return $request->user();
}); });
//接口路由
Route::match(['get', 'post'],'login', 'LoginApiController@index');
Route::match(['get', 'post'],'loginc', 'LoginCheckController@index');
Route::group(['middleware' => 'check.apikey','prefix' => 'api'], function () {
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment