Giter Club home page Giter Club logo

php-auth's Issues

automatic login after email verification

Hello,

From a user experience point of view it may be a bit bothersome to have to login right after the "registration and verification of email address" process.

I thought about storing the email/password in sessions variables to automatically log the user in right after checking the token/selector for the email verification but this seems to create security issues (ie: storing a plain text password somewhere). Is there a better way to do this?

Is there a security reason for it not being already implemented?

Thanks.

Adding support for roles

We should add support for user roles to this library soon. A list of available roles can be hard-coded and could look like this:

final class Role {

	const ADMIN = 1;
	const AUTHOR = 2;
	const COLLABORATOR = 4;
	const CONSULTANT = 8;
	const CONSUMER = 16;
	const CONTRIBUTOR = 32;
	const COORDINATOR = 64;
	const CREATOR = 128;
	const DEVELOPER = 256;
	const DIRECTOR = 512;
	const EDITOR = 1024;
	const EMPLOYEE = 2048;
	const MAINTAINER = 4096;
	const MANAGER = 8192;
	const MODERATOR = 16384;
	const PUBLISHER = 32768;
	const REVIEWER = 65536;
	const SUBSCRIBER = 131072;
	const SUPER_ADMIN = 262144;
	const SUPER_EDITOR = 524288;
	const SUPER_MODERATOR = 1048576;
	const TRANSLATOR = 2097152;

	private function __construct() {}

}

You can then use any of these roles and ignore those that you don't need, and you can even combine these roles as you like. Thus a user may have none of these rules, one role or any other arbitrary subset.

Although a fixed set of roles is hard-coded in this implementation, the set of roles should include identifiers for most use cases. And if you really can't work with these roles, you can alias them using your own role identifiers:

final class MyRole {

	const CUSTOMER_SERVICE_AGENT = Role::REVIEWER;
	const FINANCIAL_DIRECTOR = Role::COORDINATOR;

	private function __construct() {}

}

That, for example, would allow you to use MyRole::FINANCIAL_DIRECTOR instead of Role::COORDINATOR.

Checking for roles that the current user has might then be done like this:

/** @var Auth $auth */

if ($auth->hasRole(Role::ADMIN)) {
	// ...
}

// or

if ($auth->hasAnyRole(Role::MODERATOR, Role::SUPER_MODERATOR, Role::ADMIN)) {
	// ...
}

// or

if ($auth->hasAllRoles(Role::TRANSLATOR, Role::REVIEWER)) {
	// ...
}

This feature would not include support for permissions, capabilities, access rights or privileges. These could be added with custom solutions in user code or one could go entirely without them. As can be seen above, it's possible to implement access restrictions using roles only. The privileges are then encoded in the conditions that specify the required roles.

Since the roles require database changes (at least one new column in the users table) that must be applied manually, this is a breaking change that can only be in a new major release. The next one would currently be v5.0.0.

Feedback, requests for additions/changes and criticism is welcome!

doesn't work with two installations on one domain.

If you try to use the library on two websites sharing one domain (ex.: domain.com and sub.domain.com), after authorisation on domain.com you go to sub.domain.com and login fails every time no matter what.
This happens when two sessions are active. If you go to the Developer Tools and remove both sessions from cookies, authorization starts working. But again until you get two sessions on both installations active again. Which happens to me quite often.

Password challenge

Hello

Just a quick feature suggestion: the ability to challenge a user for a password without proceeding through a complete login process.

For example, imagine that a user is already authenticated because they are remembered. But now the user accesses a "dangerous" or "significant" feature (such as linking a bank account). It would be good to challenge the user for their password again to ensure that it is not an imposter using a shared computer, for instance.

Browsing the internals of Auth.php I see that this can be done by password_verify($password, $userData['password']). However, perhaps there is some more reusable logic that may be helpful. Or if the password hashing changes, it would be good to encapsulate it all in one place...

Thx

issue when using "localhost"

I had a tiny issue when using localhost as domain.

It seemed like the parameters couldn't be pushed into a cookie. I just quickly debugged it in the "login" method. Maybe some further investigation will be necessary.

Just wanted to let u know.

I used it with a ordinary XAMPP stack with PHP 7 - just to make this information useful.

Great lib btw! 👍

Failing to check if email is verified

In Auth.php the authenticateUserInternal method is failing to check if user column 'verified' is set to 1 because it is strictly comparing a string with an integer:

if ($userData['verified'] === 1) {

should have been casted to an integer:

if ((int)$userData['verified'] === 1) {

is it correct?

[NFR] Getter & setter for \Delight\Db\PdoDatabase::$attributes.

Hi,

Thanks for a nice auth library.

I need an ability to modify PDO attributes - MySQL does not support PDO::ATTR_STRINGIFY_FETCHES.

Please implement:

In \Delight\Db\PdoDatabase:

/**
 * Set single PDO attribute.
 *
 * @param integer $key PDO attribute
 * @param integer $val PDO attribute value
 * @return $this
 */
public function setAttribute($key, $val)
{
    $this->attributes[$key] = $val;
    return $this;
}

/**
 * Set PDO attributes array.
 *
 * @param array $val PDO attributes in key/value format.
 * @return $this
 */
public function setAttributes(array $val = null)
{
    $this->attributes = $val;
    return $this;
}

/**
 * Get PDO attribute value.
 *
 * @param integer $key PDO attribute
 * @return mixed
 */
public function getAttribute($key)
{
    if (isset($this->attributes[$key])) {
        return $this->attributes[$key];
    }
}
/**
 * Get all PDO attributes.
 *
 * @return array|null
 */
public function getAttributes()
{
    return $this->attributes;
}

In Delight\Auth\Auth:

/**
 * @return PdoDatabase
 */
public function getDb()
{
    return $this->db;
}

Thanks!

Ensure account is verified before initiating password reset

I have an app that requires admin-approval of user accounts. The email verification already built into PHP-Auth works great for this (verification links sent to admins instead of users).

This brings up the use case where a user may register, then attempt to reset their password prior to the account being verified (could also occur for user email verification as well, although perhaps less often). I modified Auth::forgotPassword as follows to check if the account is verified before initiating the password reset process:

public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) {
		$email = self::validateEmailAddress($email);

		if ($requestExpiresAfter === null) {
			// use six hours as the default
			$requestExpiresAfter = 60 * 60 * 6;
		}
		else {
			$requestExpiresAfter = (int) $requestExpiresAfter;
		}

		if ($maxOpenRequests === null) {
			// use two requests per user as the default
			$maxOpenRequests = 2;
		}
		else {
			$maxOpenRequests = (int) $maxOpenRequests;
		}

		// Ensure account is verified before initiating password reset
		try {
			$userData = $this->db->selectRow(
				'SELECT id, verified FROM users WHERE email = ?',
				[ $email ]
			);
		}
		catch (Error $e) {
			throw new DatabaseError();
		}

		if ($userData['verified'] !== 1) {
			throw new EmailNotVerifiedException();
		}

		$userId =  $userData["id"];
		// $userId = $this->getUserIdByEmailAddress($email); // no longer needed
		$openRequests = (int) $this->getOpenPasswordResetRequests($userId);

		if ($openRequests < $maxOpenRequests) {
			$this->createPasswordResetRequest($userId, $requestExpiresAfter, $callback);
		}
		else {
			self::onTooManyRequests($requestExpiresAfter);
		}
	}

And made sure to catch the new error in the $auth->forgotPassword handler:

try {
	$auth->forgotPassword($_POST['email'], function ($selector, $token) {
			// send `$selector` and `$token` to the user (e.g. via email)
	});

	// request has been generated
}
catch (\Delight\Auth\InvalidEmailException $e) {
	// invalid email address
}
catch (\Delight\Auth\TooManyRequestsException $e) {
	// too many requests
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
	// email not verified
}

Would be happy to create a pull request if it'll help, or if there's a more optimal solution would be great to hear that too. Thank you very much for an excellent, lightweight, well-documented library!

Extending the class

Hi,

Wouldn't it be better for the methods to be protected in case you want to extend the Auth class? For example, if I want a login method with user name instead of e-mail.

User is not verified due to error.

/src/Auth.php on line 682
if ($userData['verified'] === 1) {
On one of my servers, this condition always returns false. On localhost it's ok, but on the live server, it throwed me an error. I suppose it's because MySQL alway returns strings as an output and 1 !== '1' while 1 == '1'. For some reason two my servers are dealing with this issue differently.
So I just switched from === to == and it worked.
I thought maybe it will be helpful to change.

Compatibility note for stacks without mysqlnd

Hello

I don't know much about DevOps or how common mysqlnd is in LAMP stacks, but Bluehost currently doesn't provide it out-of-the-box. The other PDO MySQL connector doesn't typecast (instead treating everything as a string) which causes a bug on if ($userData['verified'] === 1) { and if ($userData['verified'] !== 1) { in Auth.php lines 587 and 682.

Obviously the preferred solution is for users to configure the server with mysqlnd, but I just thought I'd mention this...

Inactive Users

Hello

First I'd like to express my appreciation for these very simple and extremely elegant libraries.

My question or suggestion relates to making users inactive. Rather than deleting rows, it is often preferable to set a flag for "isDeleted" or "isInactive". Storing such a column in another Users_Data table (e.g. Users_Profiles) might cause poor performance because of the join (especially when also joined with a User_Posts or User_Votes table). Would an "activeStatus" column be a candidate to be added to the main Users table in a schema update? I see you're careful to avoid bloat, but I just thought I'd suggest this. Alternatively, would it be bad form to combine this functionality with the suggested Roles feature?

Perhaps a workaround in the meantime would be to append or prepend an invalid ASCII string to the email column. Something like [[@@]] that isn't allowed in email addresses. It should still be able to query active users simply and quickly.

manual installation readme for shared servers that don't allow composer?

For the many thousands of us working on shared servers across many hosting sites, composer isn't installed or allowed without upgrading to VPS or dedicated boxes. It would be most awesome if a detailed readme could be made explaining how to install PHP-Auth manually. Obviously, the DB is easy part, although I love your idea of a table prefix option.

Would this be possible? Many thanks for your awesome work!

Questions about db schema

Hello!
First, thanks for this nice library.
I just have a couple questions about the database schema you use:

  • Is there any reason you use MyISAM over InnoDB (with foreign keys)?
  • Some columns are defined with a latin charset, is there a reason for that also? (simple curiosity)

Thank you!

header already sent problems

I have a strange fenomenon:
On one subdomain (user tests) I am using the nearly same redirects but get no errors...
On the other subdomain (integration tests) I made a fresh install with a slight change (full domain - not relative header location calls) but got weird behaviour: It's actually not redirecting...
because Auth is already sending out headers...
But I have no clue why the code works in one subdomain, but in slight variation ( header('Location http://subdomain/folder/file.php) ) it doesn't... Specially why my change would provoke a different behaviour in Auth

representative Code (produces empty page, no redirect):
PD: Fact is: after running the code I am still logged in...

$AUTH->logout();
$_SESSION['preguntas_educacion'] = NULL;
$_SESSION['preguntas_postulacion'] = NULL;
?>
<?php if ($AUTH->isLoggedIn()): ?>
    <?php 
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/paso1.php"); ?>
<?php else: ?>
    <?php 
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/login.php"); ?>
<?php endif; ?>

Error:

Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 73

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 87

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 92

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 94

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 97

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 98

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 99

Fatal error: Uncaught exception 'Delight\Auth\HeadersAlreadySentError' in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:320 Stack trace: #0 /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php(277): Delight\Auth\Auth->setRememberCookie(NULL, NULL, 1495128213) #1 /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php(371): Delight\Auth\Auth->deleteRememberDirective(50) #2 /home/user/subdomain.whatever.com/logout.php(15): Delight\Auth\Auth->logout() #3 {main} thrown in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 320

percent sign in cookie

Does auth use a non-standard way of writing the PHPSESSID cookie? I am sometimes getting a %25 (encoded %) in my cookie, which is causing an error to be displayed in unexpected places. Thanks!

Login remembered

Hallo und frohes neues Jahr für euch!
Ich versuchs mal auf deutsch, sorry.
Ich denke, dass es ein Fehlverhalten gibt, bei der Angabe des zweiten Parameters im Konstruktor.
Oder ich habs noch nicht verstanden...
Also wenn das ausgeführt wird:
$auth = new \Delight\Auth\Auth($db, true);
$auth->login($_POST['email'], $_POST['password'], null);

dann erzeugt später komischerweise $auth->check() den Wert false.
Obwohl man doch mindestens bis zum Schließen des Browsers angemeldet sein müsste.
Lediglich die Session-Variable "auth-remember" ist verfügbar!?
Wenn beim instanzieren "true" weggelassen wird, funktioniert es wie erwartet.
Das passiert sowohl lokal (XAMPP, PHP5.6) als auch bei STRATO-Hosting (SSL, PHP5.6)
Am Ende will ich eigentlich nur, dass ohne Zeitvorgabe die Session bei Beenden des Browsers zu Ende ist, also automatisch ausgeloggt wird. Ich bekomme es nicht hin ...
Can you help? ;-)

hashing mechanism

What sort of hashing mechanism is being used in php-auth?

Thanks for your time!

Change request: role const values

Last post until I hear back from the project team, promise.

Requesting a breaking change to Roles class. Please can you reorder the CONST so that the values are in numerical order from lowest to highest privilege. Ie: super administrator should be 999, administrator should be 666, and basic user should be 333, and guest should be 1 or whatever.

Doing this will allow my extend to ensure that the admin interface will only grant or edit roles less than or equal to the currently logged in user. This is a standard security control against elevation of privilege - will also allow control of user granting themself additional roles.

Appreciate that users of this library can do this themselves by aliasing the const, but they won't realize the implication of NOT doing this unless it's a) down in the code, b) shown in the docs before the check is added to the admin role grant and remove methods.

Unfortunately this will be a breaking change for anyone who uses the library today, even though it's not actually a code change in itself, it just enables a feature to be implemented.

Might also be a good time to stop using const for roles, and use a database table instead, because the const approach is very limiting for features.

Thanks

Provide a way to revoke sessions and to perform remote logouts

Whenever a user signs in, we could add the session ID, together with the ID of the user who has just logged in, to the database (into some new table that will be created for that purpose).

It might even make sense to track the IP address and user-agent string there as well, if not disabled for privacy reasons.

CREATE TABLE users_sessions (
    user_id int(10) unsigned NOT NULL,
    session_id varchar(256) CHARACTER SET latin1 NOT NULL,
    user_agent varchar(192) DEFAULT NULL,
    ip_address varchar(45) DEFAULT NULL,
    expires_at int(10) unsigned NOT NULL,
    PRIMARY KEY (user_id, session_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

In the two methods UserManager#onLoginSuccessful and Auth#logOut, we would always update the database with the latest information about the current session. That may not be enough, though. The expires_at column in the database schema is the critical piece of information here.

That would allow us to show users a list of all sessions (or devices) where they're currently logged in.

In addition to that, any of these sessions could then be killed remotely, e.g. as in the following example, which has neither been tested thoroughly nor been executed at all, though:

function destroySessionById($id) {
	$pausedSessionId = '';

	// if a session is currently active
	if (\session_id() != '') {
		// if that session is not the one we're trying to destroy
		if (\session_id() !== $id) {
			// remember which session it was that we interrupted
			$pausedSessionId = \session_id();
			// save and close that active session
			\session_write_close();
		}
	}

	// if the session to be destroyed has not been opened yet
	if (\session_id() == '') {
		// impersonate the session to be destroyed
		\session_id($id);
		// and open the session
		\session_start();
	}

	// unset the session variables
	$_SESSION = array();
	// destroy the session
	\session_destroy();
	// save and close the destroyed session
	\session_write_close();

	// if we have previously interrupted another session
	if ($pausedSessionId != '') {
		// assume that session again
		\session_id($pausedSessionId);
		// and open the session
		\session_start();
	}
}

Using those new resources, some new logOutFromAllDevices method would be possible as well.

Installation instruction not sufficient

Dear Delight-Im,

When following the instructions I keep getting an error.
I copied the files (Auth.php, Base64.php and Exceptions.php) to a subfolder.
When I run the following script however, I get the following errors, no matter what I tried.
I feel like there might be an error using the namespaces?

I run the following (I tried both instances of $db uncommented)

require 'subfolder/Auth.php';
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
// or
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');

$auth = new \Delight\Auth\Auth($db);

But I get the following errors:
Uncaught Error: Class 'Delight\Db\PdoDatabase' not found in ... Stack trace: #0 ...: Delight\Auth\Auth->__construct(Object(PDO)) #1 {main}

OR

Fatal error: Uncaught Error: Class 'Delight\Auth\PdoDsn' not found in ...
Stack trace: #0 {main}

I tried to install everything using composer but I got the some errors......

I am really looking forward to start using this package!

Cheers

Security issue (and why autoloaders are a bad idea)

For clarity, the issue is with the way examples in the docs are written, combined with the way the PHPAuth library uses your DB library. It's creating a false sense of security.

The simple version: all of the examples in the documentation directly use unchecked POST input for params. This is OK in terms of SQL injection, because the underlying DB lib uses PDO prepared statements which automagically escapes everything.

However it does NOT prevent app level security risks. For example, a user can write javascript into a param (e.g.: change my email address). The script will be escaped when written to the DB, but unescaped on read and output in original format if echo'd to a page.

Assuming you code an admin system that lists all the users with their email addresses in a table, so you can take admin actions, this is a flaw - a user can execute code in the admin view.

So anyone using this library must ensure that all user input from POST and GET etc are correctly sanitized, despite PHPAuth documentation not mentioning this and explicitly using it in the examples (and, on assumption, relying on PHPDB PDO automagic to secure input). The OWASP recommendations are a good starting point: https://www.owasp.org/index.php/OWASP_PHP_Filters

The autoloader compounds this problem. If you simply use the autoloader, you can be forgiven for not realizing that PHPAuth uses PHP DB library & what protection it actually does/does not offer. This is why autoloaders are a bad idea - you don't know what dependency code is being included in your project simply by using a library.

In summary, either the documentation needs to be changed to highlight that POST and GET must be sanitized and should absolutely not be passed to PHPAuth unchecked. Or PHP Auth must be changed so that data is properly escaped at all stages (I'd suggest this is a better option, because nobody should have a username or email address that includes < script > etc

The problem is that at the moment you have a half way solution - some issues are prevented due to PDO automagic, but other issues are not prevented. Less savvy users of this code may assume that the protection offered by PHPDB (from the docs: "Safe against SQL injections through the use of prepared statements") is sufficient, when it's absolutely not - that is, if they even realize the additional libs that are in use due to autoload.

Happy to be told I'm wrong here because I don't use PDO, I use mysqli, but looks like a gap to me.

Thinking behind logout process

Hi guys, please can you explain your thinking behind the session and cookie destruction in the logout method?

I'd suggest PHPAuth should only kill session data directly related to auth & login, not the entire session. Killing the entire session has impact on other code outside of PHPAuth. For example, if the session is used to also retain for example "last used" (e.g.: "last search terms", "id of last thing looked at"), this session data may need to be preserved.

Imagine a menu where "recent searches", "recent products viewed" is an option, and those recent searches are retained in the session (rather than a backend DB). The user may want to log out, then log in again a few mins later or even view the site from a "not logged in state", and from a user experience point of view they'd expect to still see their "recent searches".

Hard killing the session in the way you do it can also cause other problems, e.g.: with ajax requests etc. I get why you've probably done this, but you're making the assumption that only valid activities can happen following a PHPAuth login - which isn't the case in many real world applications.

Thank you

Two PHPSESSID cookies

We are having an issue with two PHPSESSID cookies being created or a previously existing PHPSESSID cookie not being cleared after we implement php-auth.

$auth->check() passes at login but subsequently fails if we do not clear one of the cookies.

This seems to be happening in two circumstances:

  1. If a user has not cleared an existing PHPSESSID cookie, created before we implemented php-auth. This may be the result of the user having the website open when we updated the code to include php-auth.
  2. If a user has a domain and subdomain open in the same browser. If we have something like abw.mywebsite.com and mywebsite.com open in the same browser then we see two PHPSESSID cookies .abw.mywebsite.com and .mywebsite.com.

$auth->check() passes at login but subsequently fails if we do not clear one of the cookies.

Any ideas on what the issue / solution may be?

change user email address

There's a way to change the current user's password.

Is there a way to change the current user's email address?

before login function

Hello,
Can we add a public function to execute before login ( true => continue, false => stop ), I'll use that to add google 2 step verification.
but I think other people will find it useful for other things

Re-send confirmation request

Very nice library! Been a breeze to integrate into my Slim3 app.

I wanted to discuss the possibility of re-sending an email confirmation request on demand after registration.
Case being where confirmation link is lost or expired before the user clicks it. In which case the user is stuck in limbo as far as I can tell.

It looks to me that this would mostly be a matter of making createConfirmationRequest public.
A DB DELETE query could also be issued on every call by default to invalidate any previous confirmation tokens for given email so that only the latest one is valid.

Are there any potential issues with this that I'm overlooking?

Best
Steini

Cookie expire problem

I have problem at remember me function. Can you please show me the exact place to set an non-expiring cookie for the login ?

DB for Doctrine entity

Ir is possible to get Mysql entity class's for Doctrine instead MySQL.sql?
Many thanks.

composer strange import

It's actually my first try with PHPAuth & Composer, so maybe I did something wrong.

I followed the install guideline as suggested and uploaded to my server.
To my astonishment when testing I was getting a
Fatal error: Call to undefined method Delight\Auth\Auth::getStatus() in /home/........./delightPHPAuth/tests/index.php on line 349

Now after some long debugging, I've found out that composer included a delight-im package, which seems not matching the one in the master tree.
the file structure is different, and the AuthClass obviously too, that's where the error came from.
So now instead of taking the AuthClass from root/src it takes it from root/vendor/delight-im/auth/src

Now the main questions is: Did I something wrong? is there even something I could do wrong?
And even better: How to do it right and correctly fix it?

Configurable database table prefix

We should introduce an optional database table prefix and make it configurable.

The default prefix will be the empty string, of course.

That option could be passed to the constructor of the Auth class as another parameter called $databaseTablePrefix.

Fixed issues, added features

There's some other security issues with this library, and it's missing a lot of admin features.

I've fixed all that, made the login system authoritative, and done some other stuff.

I also dislike how unfriendly github is, so I've done my best with the files. Good luck.

https://github.com/32Blahs/PHP-AuthExtra

Using Content-Security-Policy instead of X-Frame-Options

In "enhanceHttpSecurity" X-Frame-Options is used do prevent clickjacking. Would it be possible to use Content-Security-Policy instead?

This would allow to add exceptions without having to change PHP-AUTH or removing the X-Frame-Options and readding it with changed parameters.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors

Thank you for this amazing piece of work, I really enjoyed integrating the authentication system in some of my projects :)

Headers already sent on logout

I'm having an issue using your logout method.

I'm using an MVC pattern so there is a link on my view like http://mysite/Account/Logout from which i call logout from PHP-Auth lib.
This produce to me the error Delight\Auth\HeadersAlreadySentError, with this stack trace:

#0 C:\xampp\htdocs\auth-bcv\vendor\delight-im\auth\src\Auth.php(315): Delight\Auth\Auth->setRememberCookie(NULL, NULL, 1502959682)
#1 C:\xampp\htdocs\auth-bcv\vendor\delight-im\auth\src\Auth.php(414): Delight\Auth\Auth->deleteRememberDirective(7)
#2 C:\xampp\htdocs\auth-bcv\Controllers\AccountController.php(411): Delight\Auth\Auth->logout()
#3 C:\xampp\htdocs\auth-bcv\Routes.php(61): AuthBcv\Controllers\AccountController->LogOut(Array)
#4 C:\xampp\htdocs\auth-bcv\Routes.php(97): call('Account', 'LogOut', Array)
#5 C:\xampp\htdocs\auth-bcv\Views\Shared\_Layout.php(23): require_once('C:\\xampp\\htdocs...')
#6 C:\xampp\htdocs\auth-bcv\index.php(37): require_once('C:\\xampp\\htdocs...')
#7 {main}

that i can't understand how to solve.

How can i fix this problem? Is there something wrong in my use of logout?

Additional columns

Hello,

Is there any way to set additional data in users table during registration? It would be perfect if after sucessful login we'll receive it in Session either. Any chances to do so?

Of course I can insert additional data just after registration and then make wrapper to login method with additional SELECT statement, but maybe there is a way to do so only using PHP-Auth?

need session after log out

After logging out, I have some ajax stuff that needs session variables in order to function.

Is it normal to force a page reload after using $auth->logout();? Or is there a preferred way to regenerate the session?

Let me know if you need more info. Thanks in advance!

No test/exception for DB failure on construct

Nice library (although wish you would also include a manual include/no autoload include.php, had to do that myself and it's painful because the dir structure sprawls a bit, I don't like autoloaders....).

When instantiating a PHP-Auth, there doesn't seem to be a way to immediately test or catch whether there was an issue with the database / setup.

Testing whether the setup was ok is pretty critical for an authentication/security mechanism. If there was an error connecting to the DB or reading any data, I want to die() immediately rather than risk some unexpected insecure code flow.

For example, the following doesn't throw any exception. I tried using isLoggedIn() to force a throw, but nothing happens:

$db = new \Delight\Db\PdoDsn('mysql:dbname=SOME;host='INVALID', 'DATABASE', 'CONFIG');
$auth = new \Delight\Auth\Auth($db, SITE_HTTPS_ENFORCED, FALSE, NULL, "php_auth_");
$auth->isLoggedIn(); // should fail, but doesn't throw?

However later if I call
$auth->login("deliberately", "junkdata");

I get a Delight\Auth\DatabaseError thrown.

This seems wrong workflow to me. I understand why it happens due to PHP-DB, but in my opinion this isn't right. Regardless of lazy load in PHP-DB (which I don't use anywhere else in my code), PHP-Auth should actively check for valid DB connection on instantiation. If PHP-Auth doesn't throw when I instantiate it with all the data necessary to set up, the logical assumption is everything is working.

Ability to immediately dump out on critical error of PHP-Auth failure to access DB is essential. It creates the following scenario, for example when allowing a password reset after form submission:

$db = new \Delight\Db\PdoDsn('mysql:dbname=SOME;host='INVALID', 'DATABASE', 'CONFIG');
$auth = new \Delight\Auth\Auth($db, SITE_HTTPS_ENFORCED, FALSE, NULL, "php_auth_");
$auth->forgotPassword("irrelevant - db config is bad", function ($selector, $token)
{
// blah
});

The exception thrown is InvalidEmailException, when actually it should be DatabaseError and handled completely differently.

I'd be happy with a ->Connect method, to force immediate DB connection. There's no penalty here as you're only ever instantiating PHP-Auth when you need it for something...

The registration page keeps loading forever

register.php

<?php 
$pagetitle = 'register';
 require('database_connect.php');

$email = '[email protected]';
$password= 'somepassword';
$username='elie';

try {
    $userId = $auth->admin()->createUser($email, $password, $username);
    


    // we have signed up a new user with the ID `$userId`
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // invalid email address
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    // user already exists
}
 ?>

connect.php

<?php
require __DIR__ . '/vendor/autoload.php';
use SimpleCrud\SimpleCrud;


/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=db;host=127.0.0.1';
$user = 'root';
$password = '';

try {
    $pdo = new PDO($dsn, $user, $password);
    $db = new SimpleCrud($pdo);
    $auth = new \Delight\Auth\Auth($pdo);


} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}



?>

Also tried to edit it to match the one in readme file, same problem. nothing in database. I'm using mariadb, xampp for linux, latest version

DB agnostic? Requires mysql...

Hi there, I'm not sure what you mean by db agnostic, if there is a requirement for mysql. I see that you pass a pdo instance to the class; can i use a pdo instance of sqlserver?

Database encoding

Hi,

is it a security issue to use utf8_unicode_ci (instead of utf8mb4) for the database encoding (MySQL)?
Thanks,

Flo

What happens when Remember Me is `uncheck`?

This is more of a question than an issue. I wanted to understand the behaviour when I login using your library and Remember me is uncheck.

Will my session expire while browsing through the website? Imagine a use-case where I logged in and browser to about-us page from homepage. After landing on about-us page I should still be logged in.

Another example is of refresh. What happens when I refresh my page?

Only cases where I should be logged out is when I close my tab or browser or manually type another url in address bar. Post these user actions if I come back on the site and Remember me was uncheck I should be asked to login again.

Thanks in advance!

customizable password requirements and enforcement?

I may have missed something in the documentation but where and how is this feature implemented?
I guess I could validate passwords myself before but I see there is a catch for InvalidPasswordException, however I didn't see where to customize password requirements or where the default requirements are defined.

Any help would be appreciated as I'm trying to use this authentication system for a website.
Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.