php教程 php手册 PHP Laravel 框架 扩展自己需要的 Auth 模块

PHP Laravel 框架 扩展自己需要的 Auth 模块

Jun 06, 2016 pm 07:34 PM
auth laravel php 확장하다 액자 곰팡이 소유하다

PHPLaravel框架扩展自己需要的Auth模块 Laravel PHP Auth::extend('platform', function($app) { $provider = new \Illuminate\Auth\PlatformUserProvider( $app['db']-connection(), $app['hash'],$app['config']['auth.table']); return new \Illuminate\Au

PHP Laravel 框架 扩展自己需要的 Auth 模块 Laravel PHP
Auth::extend('platform', function($app) {
    $provider =  new \Illuminate\Auth\PlatformUserProvider( 
		$app['db']->connection(), 
		$app['hash'],
		$app['config']['auth.table']
		);
    return new \Illuminate\Auth\Guard($provider, App::make('session.store') );
});
로그인 후 복사
<?php namespace Illuminate\Auth;

//放在Laravel/项目名/vendor/laravel/framework/src/Illuminate/Auth 下 ,存名 PlatformUserProvider.php

use Illuminate\Database\Connection;
use Illuminate\Hashing\HasherInterface;
use Illuminate\Auth\GenericUser;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\UserProviderInterface;


class PlatformUserProvider implements UserProviderInterface
{

	/**
	 * The active database connection.
	 *
	 * @param  \Illuminate\Database\Connection
	 */
	protected $conn;

	/**
	 * The hasher implementation.
	 *
	 * @var \Illuminate\Hashing\HasherInterface
	 */
	protected $hasher;

	/**
	 * The table containing the users.
	 *
	 * @var string
	 */
	protected $table;

	/**
	 * Create a new database user provider.
	 *
	 * @param  \Illuminate\Database\Connection  $conn
	 * @param  \Illuminate\Hashing\HasherInterface  $hasher
	 * @param  string  $table
	 * @return void
	 */
	public function __construct( Connection $conn, HasherInterface $hasher, $table )
	{
		$this->conn = $conn;
		$this->table = $table;
		$this->hasher = $hasher;
	}

	/**
	 * Retrieve a user by their unique identifier.
	 *
	 * @param  mixed  $identifier
	 * @return \Illuminate\Auth\UserInterface|null
	 */
	public function retrieveById($identifier)
	{
		$user = $this->conn->table($this->table)->find($identifier);

		if ( ! is_null($user))
		{
			return new GenericUser((array) $user);
		}
	}

	/**
	 * Retrieve a user by by their unique identifier and "remember me" token.
	 *
	 * @param  mixed  $identifier
	 * @param  string  $token
	 * @return \Illuminate\Auth\UserInterface|null
	 */
	public function retrieveByToken($identifier, $token)
	{
		$user = $this->conn->table($this->table)
                                ->where('id', $identifier)
                                ->where('remember_token', $token)
                                ->first();

		if ( ! is_null($user))
		{
			return new GenericUser((array) $user);
		}
	}

	/**
	 * Update the "remember me" token for the given user in storage.
	 *
	 * @param  \Illuminate\Auth\UserInterface  $user
	 * @param  string  $token
	 * @return void
	 */
	public function updateRememberToken(UserInterface $user, $token)
	{
		$this->conn->table($this->table)
                            ->where('id', $user->getAuthIdentifier())
                            ->update(array('remember_token' => $token));
	}

	/**
	 * Retrieve a user by the given credentials.
	 *
	 * @param  array  $credentials
	 * @return \Illuminate\Auth\UserInterface|null
	 */
	public function retrieveByCredentials(array $credentials)
	{
		// First we will add each credential element to the query as a where clause.
		// Then we can execute the query and, if we found a user, return it in a
		// generic "user" object that will be utilized by the Guard instances.
		$query = $this->conn->table($this->table);

		foreach ($credentials as $key => $value)
		{
			if ( ! str_contains($key, 'login_pwd'))
			{
				$query->where($key, $value);
				
			}
		}

		// Now we are ready to execute the query to see if we have an user matching
		// the given credentials. If not, we will just return nulls and indicate
		// that there are no matching users for these given credential arrays.
		$user = $query->first();

		if ( ! is_null($user))
		{
			return new GenericUser((array) $user);
		}		
	}

	/**
	 * Validate a user against the given credentials.
	 *
	 * @param  \Illuminate\Auth\UserInterface  $user
	 * @param  array  $credentials
	 * @return bool
	 */
	public function validateCredentials(UserInterface $user, array $credentials)
	{
		$plain = $credentials['login_pwd'];
		return $this->hasher->check($plain, $user->getAuthPassword());
	}

}
로그인 후 복사
<?php namespace Illuminate\Auth;

class GenericUser implements UserInterface {

	/**
	 * All of the user's attributes.
	 *
	 * @var array
	 */
	protected $attributes;

	/**
	 * Create a new generic User object.
	 *
	 * @param  array  $attributes
	 * @return void
	 */
	public function __construct(array $attributes)
	{
		$this->attributes = $attributes;
	}

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->attributes['id'];
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->attributes['login_pwd'];
	}

	/**
	 * Get the token value for the "remember me" session.
	 *
	 * @return string
	 */
	public function getRememberToken()
	{
		return $this->attributes['remember_token'];
	}

	/**
	 * Set the token value for the "remember me" session.
	 *
	 * @param  string  $value
	 * @return void
	 */
	public function setRememberToken($value)
	{
		$this->attributes['remember_token'] = $value;
	}

	/**
	 * Get the column name for the "remember me" token.
	 *
	 * @return string
	 */
	public function getRememberTokenName()
	{
		return 'remember_token';
	}

	/**
	 * Dynamically access the user's attributes.
	 *
	 * @param  string  $key
	 * @return mixed
	 */
	public function __get($key)
	{
		return $this->attributes[$key];
	}

	/**
	 * Dynamically set an attribute on the user.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
	public function __set($key, $value)
	{
		$this->attributes[$key] = $value;
	}

	/**
	 * Dynamically check if a value is set on the user.
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public function __isset($key)
	{
		return isset($this->attributes[$key]);
	}

	/**
	 * Dynamically unset a value on the user.
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public function __unset($key)
	{
		unset($this->attributes[$key]);
	}

}
로그인 후 복사
<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Default Authentication Driver
	|--------------------------------------------------------------------------
	|
	| This option controls the authentication driver that will be utilized.
	| This driver manages the retrieval and authentication of the users
	| attempting to get access to protected areas of your application.
	|
	| Supported: "database", "eloquent"
	|
	*/

	//'driver' => 'eloquent',
	//'driver' => 'database',
	'driver' => 'platform',
//这里改成自己的driver
	/*
	|--------------------------------------------------------------------------
	| Authentication Model
	|--------------------------------------------------------------------------
	|
	| When using the "Eloquent" authentication driver, we need to know which
	| Eloquent model should be used to retrieve your users. Of course, it
	| is often just the "User" model but you may use whatever you like.
	|
	*/

	'model' => 'User',

	/*
	|--------------------------------------------------------------------------
	| Authentication Table
	|--------------------------------------------------------------------------
	|
	| When using the "Database" authentication driver, we need to know which
	| table should be used to retrieve your users. We have chosen a basic
	| default value but you may easily change it to any table you like.
	|
	*/

	//'table' => 'users',
	'table' => 'members',
	/*
	|--------------------------------------------------------------------------
	| Password Reminder Settings
	|--------------------------------------------------------------------------
	|
	| Here you may set the settings for password reminders, including a view
	| that should be used as your password reminder e-mail. You will also
	| be able to set the name of the table that holds the reset tokens.
	|
	| The "expire" time is the number of minutes that the reminder should be
	| considered valid. This security feature keeps tokens short-lived so
	| they have less time to be guessed. You may change this as needed.
	|
	*/

	'reminder' => array(

		'email' => 'emails.auth.reminder',

		'table' => 'password_reminders',

		'expire' => 60,

	),

);
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. 크로스 플레이가 있습니까?
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

CSRF (Cross-Site Request Grospory) 란 무엇이며 PHP에서 CSRF 보호를 어떻게 구현합니까? CSRF (Cross-Site Request Grospory) 란 무엇이며 PHP에서 CSRF 보호를 어떻게 구현합니까? Apr 07, 2025 am 12:02 AM

PHP에서는 예측할 수없는 토큰을 사용하여 CSRF 공격을 효과적으로 방지 할 수 있습니다. 특정 방법은 다음과 같습니다. 1. 형태로 CSRF 토큰을 생성하고 포함시킨다. 2. 요청을 처리 할 때 토큰의 유효성을 확인하십시오.

php에서 엄격한 유형을 설명하십시오 (strict_types = 1);). php에서 엄격한 유형을 설명하십시오 (strict_types = 1);). Apr 07, 2025 am 12:05 AM

php의 엄격한 유형은 declare (strict_types = 1)를 추가하여 활성화됩니다. 파일 상단에서. 1) 함정 유형 변환을 방지하기 위해 함수 매개 변수 및 리턴 값의 검사 유형 검사를 강요합니다. 2) 엄격한 유형을 사용하면 코드의 신뢰성과 예측 가능성을 향상시키고 버그를 줄이며 유지 관리 및 가독성을 향상시킬 수 있습니다.

클래스가 확장되지 않거나 방법이 PHP에서 무시되지 않도록하려면 어떻게해야합니까? (최종 키워드) 클래스가 확장되지 않거나 방법이 PHP에서 무시되지 않도록하려면 어떻게해야합니까? (최종 키워드) Apr 08, 2025 am 12:03 AM

PHP에서 최종 키워드는 클래스가 상속되고 메소드가 덮어 쓰는 것을 방지하는 데 사용됩니다. 1) 클래스를 최종적으로 표시 할 때는 수업을 상속받을 수 없습니다. 2) 메소드를 최종으로 표시 할 때는 메소드를 서브 클래스로 다시 작성할 수 없습니다. 최종 키워드를 사용하면 코드의 안정성과 보안이 보장됩니다.

PHP의 미래 : 적응 및 혁신 PHP의 미래 : 적응 및 혁신 Apr 11, 2025 am 12:01 AM

PHP의 미래는 새로운 기술 트렌드에 적응하고 혁신적인 기능을 도입함으로써 달성 될 것입니다. 1) 클라우드 컴퓨팅, 컨테이너화 및 마이크로 서비스 아키텍처에 적응, Docker 및 Kubernetes 지원; 2) 성능 및 데이터 처리 효율을 향상시키기 위해 JIT 컴파일러 및 열거 유형을 도입합니다. 3) 지속적으로 성능을 최적화하고 모범 사례를 홍보합니다.

Bangla 부분 모델 검색의 Laravel Eloquent Orm) Bangla 부분 모델 검색의 Laravel Eloquent Orm) Apr 08, 2025 pm 02:06 PM

Laraveleloquent 모델 검색 : 데이터베이스 데이터를 쉽게 얻을 수 있습니다. 이 기사는 데이터베이스에서 데이터를 효율적으로 얻는 데 도움이되는 다양한 웅변 모델 검색 기술을 자세히 소개합니다. 1. 모든 기록을 얻으십시오. 모든 () 메소드를 사용하여 데이터베이스 테이블에서 모든 레코드를 가져옵니다. 이것은 컬렉션을 반환합니다. Foreach 루프 또는 기타 수집 방법을 사용하여 데이터에 액세스 할 수 있습니다 : Foreach ($ postas $ post) {echo $ post->

Laravel 's geospatial : 대화식지도의 최적화 및 많은 양의 데이터 Laravel 's geospatial : 대화식지도의 최적화 및 많은 양의 데이터 Apr 08, 2025 pm 12:24 PM

7 백만 레코드를 효율적으로 처리하고 지리 공간 기술로 대화식지도를 만듭니다. 이 기사는 Laravel과 MySQL을 사용하여 7 백만 개 이상의 레코드를 효율적으로 처리하고 대화식지도 시각화로 변환하는 방법을 살펴 봅니다. 초기 챌린지 프로젝트 요구 사항 : MySQL 데이터베이스에서 7 백만 레코드를 사용하여 귀중한 통찰력을 추출합니다. 많은 사람들이 먼저 프로그래밍 언어를 고려하지만 데이터베이스 자체를 무시합니다. 요구 사항을 충족시킬 수 있습니까? 데이터 마이그레이션 또는 구조 조정이 필요합니까? MySQL이 큰 데이터로드를 견딜 수 있습니까? 예비 분석 : 주요 필터 및 속성을 식별해야합니다. 분석 후, 몇 가지 속성만이 솔루션과 관련이 있음이 밝혀졌습니다. 필터의 타당성을 확인하고 검색을 최적화하기위한 제한 사항을 설정했습니다. 도시를 기반으로 한지도 검색

PHP vs. Python : 차이점 이해 PHP vs. Python : 차이점 이해 Apr 11, 2025 am 12:15 AM

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오 PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오 Apr 13, 2025 am 12:20 AM

PHP는 현대 웹 개발, 특히 컨텐츠 관리 및 전자 상거래 플랫폼에서 중요합니다. 1) PHP는 Laravel 및 Symfony와 같은 풍부한 생태계와 강력한 프레임 워크 지원을 가지고 있습니다. 2) Opcache 및 Nginx를 통해 성능 최적화를 달성 할 수 있습니다. 3) PHP8.0은 성능을 향상시키기 위해 JIT 컴파일러를 소개합니다. 4) 클라우드 네이티브 애플리케이션은 Docker 및 Kubernetes를 통해 배포되어 유연성과 확장 성을 향상시킵니다.

See all articles