Commit 7db4a661 authored by UtopiaXC's avatar UtopiaXC

新增Redis与Cache切换工具

parent e0a268b9
...@@ -3,23 +3,19 @@ ...@@ -3,23 +3,19 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Utils\R; use App\Http\Utils\R;
use App\Http\Utils\RedisAndCache;
use App\Models\Users\User; use App\Models\Users\User;
use App\Models\Users\UserProfile; use App\Models\Users\UserProfile;
use Exception; use Exception;
use HTTP_CODE; use HTTP_CODE;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Predis\Connection\ConnectionException;
use RedisCacheKey; use RedisCacheKey;
use Webpatser\Uuid\Uuid; use Webpatser\Uuid\Uuid;
class UserController extends Controller class UserController extends Controller {
{ function register(Request $request) {
function register(Request $request)
{
if (!CaptchaController::check_captcha($request->get("captcha"), $request->cookie(app()->getNamespace() . "session"))) { if (!CaptchaController::check_captcha($request->get("captcha"), $request->cookie(app()->getNamespace() . "session"))) {
return R::error(HTTP_CODE::UNAUTHORIZED_CAPTCHA); return R::error(HTTP_CODE::UNAUTHORIZED_CAPTCHA);
} }
...@@ -58,8 +54,7 @@ class UserController extends Controller ...@@ -58,8 +54,7 @@ class UserController extends Controller
return R::ok(); return R::ok();
} }
function login(Request $request) function login(Request $request) {
{
if (!CaptchaController::check_captcha($request->get("captcha"), $request->cookie(app()->getNamespace() . "session"))) { if (!CaptchaController::check_captcha($request->get("captcha"), $request->cookie(app()->getNamespace() . "session"))) {
return R::error(HTTP_CODE::UNAUTHORIZED_CAPTCHA); return R::error(HTTP_CODE::UNAUTHORIZED_CAPTCHA);
} }
...@@ -81,13 +76,7 @@ class UserController extends Controller ...@@ -81,13 +76,7 @@ class UserController extends Controller
$token = md5($user[0]->id . md5(microtime(true))); $token = md5($user[0]->id . md5(microtime(true)));
$cookie = Cookie::make(\CookieKey::USER_TOKEN, $token, 60 * 24 * 30); $cookie = Cookie::make(\CookieKey::USER_TOKEN, $token, 60 * 24 * 30);
$expiredMinutes = 60 * 24 * 30; $expiredMinutes = 60 * 24 * 30;
$expiredAt = now()->addMinute($expiredMinutes); RedisAndCache::setWithExpire(RedisCacheKey::USER_TOKEN . $token, $user[0], $expiredMinutes);
try {
Redis::setex(RedisCacheKey::USER_TOKEN . $token, $expiredMinutes * 60, $user[0]);
} catch (ConnectionException $e) {
Cache::put(RedisCacheKey::USER_TOKEN . $token, $user[0], $expiredAt);
return R::ok()->withCookie($cookie);
}
return R::ok()->withCookie($cookie); return R::ok()->withCookie($cookie);
} }
} }
...@@ -2,13 +2,11 @@ ...@@ -2,13 +2,11 @@
namespace App\Http\Middleware\View; namespace App\Http\Middleware\View;
use App\Http\Utils\RedisAndCache;
use App\Models\System\SiteProfile; use App\Models\System\SiteProfile;
use Cache;
use Closure; use Closure;
use HeaderKey; use HeaderKey;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Predis\Connection\ConnectionException;
use RedisCacheKey; use RedisCacheKey;
class SiteProfileMiddleware class SiteProfileMiddleware
...@@ -23,23 +21,10 @@ class SiteProfileMiddleware ...@@ -23,23 +21,10 @@ class SiteProfileMiddleware
public function handle(Request $request, Closure $next) public function handle(Request $request, Closure $next)
{ {
//通过Redis获取网站配置信息,如果没有则存入Redis $site_profile=RedisAndCache::getWithJson(RedisCacheKey::SITE_PROFILE);
if (env(\EnvKey::REDIS_USE, false) == true) {
try {
$site_profile = json_decode(Redis::get(RedisCacheKey::SITE_PROFILE), true);
} catch (ConnectionException $e) {
$site_profile = json_decode(Cache::get(RedisCacheKey::SITE_PROFILE), true);
}
}else{
$site_profile = json_decode(Cache::get(RedisCacheKey::SITE_PROFILE), true);
}
if (!$site_profile) { if (!$site_profile) {
$site_profile = SiteProfile::all(); $site_profile = SiteProfile::all();
try { RedisAndCache::set(RedisCacheKey::SITE_PROFILE,$site_profile);
Redis::set(RedisCacheKey::SITE_PROFILE, $site_profile);
} catch (ConnectionException $e) {
Cache::put(RedisCacheKey::SITE_PROFILE, $site_profile);
}
} }
$profiles = []; $profiles = [];
foreach ($site_profile as $profile) { foreach ($site_profile as $profile) {
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
namespace App\Http\Middleware\View; namespace App\Http\Middleware\View;
use App\Http\Utils\RedisAndCache;
use Closure; use Closure;
use CookieKey;
use HeaderKey; use HeaderKey;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis; use RedisCacheKey;
use Predis\Connection\ConnectionException;
class UserAuthMiddleware class UserAuthMiddleware {
{
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
...@@ -17,26 +17,16 @@ class UserAuthMiddleware ...@@ -17,26 +17,16 @@ class UserAuthMiddleware
* @param \Closure $next * @param \Closure $next
* @return mixed * @return mixed
*/ */
public function handle(Request $request, Closure $next) public function handle(Request $request, Closure $next) {
{ $token = $request->cookie(CookieKey::USER_TOKEN);
$token = $request->cookie(\CookieKey::USER_TOKEN);
if (!$token) { if (!$token) {
$request->attributes->add([HeaderKey::LOGIN_STATUS => false]); $request->attributes->add([HeaderKey::LOGIN_STATUS => false]);
} }
$user = RedisAndCache::get(RedisCacheKey::USER_TOKEN . $token);
if (env(\EnvKey::REDIS_USE, false) == true) {
try {
$user = json_decode(Redis::get(\RedisCacheKey::USER_TOKEN . $token), true);
} catch (ConnectionException $e) {
$user = json_decode(\Cache::get(\RedisCacheKey::USER_TOKEN . $token), true);
}
}else{
$user = json_decode(\Cache::get(\RedisCacheKey::USER_TOKEN . $token), true);
}
if (!$user) if (!$user)
$request->attributes->add([HeaderKey::LOGIN_STATUS => false]); $request->attributes->add([HeaderKey::LOGIN_STATUS => false]);
else else
$request->attributes->add([HeaderKey::LOGIN_STATUS => true, HeaderKey::USER_INFO=>$user]); $request->attributes->add([HeaderKey::LOGIN_STATUS => true, HeaderKey::USER_INFO => $user]);
return $next($request); return $next($request);
} }
} }
<?php
namespace App\Http\Utils;
use EnvKey;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Predis\Connection\ConnectionException;
class RedisAndCache {
public static function set($key, $value) {
try {
if (env(EnvKey::REDIS_USE, false) == true) {
try {
Redis::set($key, $value);
} catch (ConnectionException $e) {
Cache::put($key, $value);
}
} else {
Cache::put($key, $value);
}
} catch (Exception $e) {
return false;
}
return true;
}
public static function setWithExpire($key, $value, $expireInMinutes) {
try {
$expiredAt = now()->addMinutes($expireInMinutes);
if (env(EnvKey::REDIS_USE, false) == true) {
try {
Redis::setex($key, $expireInMinutes * 60, $value);
} catch (ConnectionException $e) {
Cache::put($key, $value, $expiredAt);
}
} else {
Cache::put($key, $value, $expiredAt);
}
} catch (Exception $e) {
return false;
}
return true;
}
public static function get($key) {
try {
if (env(EnvKey::REDIS_USE, false) == true) {
try {
$value = Redis::get($key);
} catch (ConnectionException $e) {
$value = Cache::get($key);
}
} else {
$value = Cache::get($key);
}
} catch (Exception $e) {
return null;
}
return $value;
}
public static function getWithJson($key) {
try {
if (env(EnvKey::REDIS_USE, false) == true) {
try {
$value = json_decode(Redis::get($key), true);
} catch (ConnectionException $e) {
$value = json_decode(Cache::get($key), true);
}
} else {
$value = json_decode(Cache::get($key), true);
}
} catch (Exception $e) {
return null;
}
return $value;
}
}
...@@ -7,20 +7,21 @@ use Illuminate\Contracts\Queue\ShouldQueue; ...@@ -7,20 +7,21 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
class VerityLinkMail extends Mailable class VerityLinkMail extends Mailable {
{
use Queueable, SerializesModels; use Queueable, SerializesModels;
protected $link; protected $link;
protected $user;
/** /**
* Create a new message instance. * Create a new message instance.
* *
* @return void * @return void
*/ */
public function __construct($link) public function __construct($link, $user) {
{
// //
$this->$link=$link; $this->$user = $user;
$this->$link = $link;
} }
/** /**
...@@ -28,8 +29,10 @@ class VerityLinkMail extends Mailable ...@@ -28,8 +29,10 @@ class VerityLinkMail extends Mailable
* *
* @return $this * @return $this
*/ */
public function build() public function build() {
{ return $this->view('email.register_verify_link')->with([
return $this->view('email.verify_link'); "link" => $this->link,
"user" => $this->user,
]);
} }
} }
@extends('root.root')
@section('title') - 注册验证 @endsection
@section('body')
注册验证页
@endsection
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" > <html lang="{{ str_replace('_', '-', app()->getLocale()) }}" >
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>CodePen - Material VCard</title> <title>CodePen - Material VCard</title>
...@@ -112,7 +112,7 @@ ...@@ -112,7 +112,7 @@
height: 100%; height: 100%;
} }
.cards .card-content .col { .cards .card-content .col {
width: 50%; width: 70%;
height: 100%; height: 100%;
display: table-cell; display: table-cell;
transition: 0.3s ease 0.3s; transition: 0.3s ease 0.3s;
...@@ -255,15 +255,15 @@ ...@@ -255,15 +255,15 @@
<body> <body>
<div class="cards"> <div class="cards">
<div class="contact">Utopia Open Platform</div> <div class="contact" onclick="window.open('{{env('APP_URL','https://open.utopiaxc.cn/')}}')">Utopia Open Platform</div>
<div class="card active" id="overview"> <div class="card active">
<div class="card-content"> <div class="card-content">
<div class="row"> <div class="row">
<div class="left col"> <div class="left col">
<h2>Personal <strong>Social Card</strong></h2> <h2>欢迎注册<br>{{env('APP_SHOW_NAME','Utopia Open Platform')}}</h2>
<p>Click one of the social icons below to switch between card or click Contact Me link to show the contact form card. <br /><em>Make sure you're running this experiment in the latest Chrome browser.</em></p> <p>亲爱的 {{$user}}<br>您已成功注册{{env('APP_SHOW_NAME','Utopia Open Platform')}}的账户,请点击<a target="_blank" href="{{$link}}">验证链接</a>来激活您的账户功能。验证有效期十五分钟。 <br/><em>如果您点击链接后未跳转,请将以下链接复制到浏览器访问:<br>{{$link}}</em></p>
</div> </div>
<div class="right col"> <div class="right col">
......
...@@ -13,7 +13,7 @@ use Illuminate\Support\Facades\Route; ...@@ -13,7 +13,7 @@ use Illuminate\Support\Facades\Route;
| |
*/ */
Route::group(['prefix'=>'/','middleware'=>[Middleware::SITE_PROFILE_MIDDLEWARE,Middleware::AUTH_MIDDLEWARE]],function (){ Route::group(['prefix' => '/', 'middleware' => [Middleware::SITE_PROFILE_MIDDLEWARE, Middleware::AUTH_MIDDLEWARE]], function () {
Route::get('/', function () { Route::get('/', function () {
return view('index'); return view('index');
}); });
...@@ -23,4 +23,7 @@ Route::group(['prefix'=>'/','middleware'=>[Middleware::SITE_PROFILE_MIDDLEWARE,M ...@@ -23,4 +23,7 @@ Route::group(['prefix'=>'/','middleware'=>[Middleware::SITE_PROFILE_MIDDLEWARE,M
Route::get("/register", function () { Route::get("/register", function () {
return view('register'); return view('register');
}); });
Route::get("/register_verify", function () {
return view('email.register_verify');
});
}); });
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