Giter Site home page Giter Site logo

atk4 / login Goto Github PK

View Code? Open in Web Editor NEW
26.0 11.0 22.0 718 KB

Add-on implementing User Login, Registration, Management and Password

Home Page: https://agiletoolkit.org

License: MIT License

Gherkin 2.66% PHP 89.77% HTML 4.36% Pug 3.21%
authentication login php atk4 agile

login's Introduction

ATK UI implements a high-level User Interface for Web App - such as Admin System. One of the most common things for the Admin system is a log-in screen.

Although you can implement log-in form easily, this add-on does everything for you:

Installation

Install through composer composer require atk4/login

Then add Auth into your app and set appropriate user controller:

$app = new \Atk4\Ui\App();
$app->initLayout([\Atk4\Ui\Layout\Admin::class]);
$app->db = new \Atk4\Data\Persistence($dsn);

// ADD THIS CODE:
$app->auth = new \Atk4\Login\Auth($app);
$app->auth->setModel(new \Atk4\Login\Model\User($app->db));

// The rest of YOUR UI code will now be protected
\Atk4\Ui\Crud::addTo($app)->setModel(new Client($app->db));

(If you do not have User model yet, you can extend or use \Atk4\Login\Model\User).

Login

Features

Here are all the classes implemented:

  • Full transparent authentication
    • Populates user menu with name of current user
    • Adds log-out link
    • Adds Preferences page
  • Flexible ACL support
  • Model\User - basic user entity that can be extended
  • LoginForm - username/password login form
  • RegisterForm - registration form
  • Auth - authentication controller, verify and record logged state
  • UserAdmin - UI for user administration
  • Layout\Narrow - Fomantic-UI based narrow responsive layout login/registration forms
  • Templates for forms an messages
  • Demos for all of the above

When used default installation, it will relay on various other components (such as LoginForm), however you can also use those components individually.

Advanced Usage

There are two modes of operation - Automated and Manual. Automated handles display of forms based on currently logged state automatically. It was already presented in the "Installation" section above.

For a more advanced usage, you can either tweak Automated mode or use individual components manually.

Tweaking Automated Mode

When you initialize 'Auth' class you may inject property values:

$app->auth = new \Atk4\Login\Auth($app, [
    'hasPreferences' => false, // do not show Preferences page/form
    'pageDashboard' => 'dashboard', // name of the page, where user arrives after login
    'pageExit' => 'goodbye', // where to send user after logout

    // Oter options:
    // 'hasUserMenu' => false, // will disable interaction with Admin Layout user menu
]);
$app->auth->setModel(new User($app->db));

Using Manual Mode

In the manual mode, no checks will be performed, and you are responsible for authenticating user yourself. This works best if you have a more complex auth logic.

$app->auth = new \Atk4\Login\Auth($app, [
    'check' => false,
]);
$app->auth->setModel(new User($app->db));


// Now manually use login logic
if (!$app->auth->user->isLoaded()) {
    \Atk4\Login\LoginForm::addTo($app, ['auth' => $app->auth]);
}

Adding sign-up form

\Atk4\Login\RegisterForm::addTo($app)
    ->setModel(new \Atk4\Login\Model\User($app->db));

Displays email and 2 password fields (for confirmation). If filled successfully will create new record for \Atk4\Login\Model\User. Will cast email to lowercase before adding. Things to try:

  • Extend or use your own User class
  • Add more fields to registration form
  • Decorate registration form with message and links
  • Use multi-column form layout

Log-in form

Login

\Atk4\Login\LoginForm::addTo($app, [
    'auth' => $app->auth,
    // 'successLink' => ['dashboard'],
    // 'forgotLink' => ['forgot'],
]);

Displays log-in form and associate it with $auth. When form is filled, will attempt to authenticate using $auth's model. If password is typed correctly, will redirect to "successLink" (which will be passed to $app->url()). Things to try:

  • Redirect to login page if not authenticated
  • Add 3rd party authentication (authenticate using 3rd party lib, look up connected account, store into auth persistence)
  • Implement two factor authentication (store flag in auth persistence indicating if 2nd factor is carried out, if not display it)
  • Implement password verification delay after several unsuccessful attempts
  • Ask user to change password if it is about to expire

Dashboard

To check if user is currently logged in:

if ($app->auth->user->isLoaded()) {
    // logged-in
}

Auth model stores user model data in session, so if you delete user from database, he will not be automatically logged out. To log-out user explicitly, call $app->auth->logout().

You may also access user data like this: $app->auth->model['name']; Things to try:

  • Explicitly load user record from database instead of cache only
  • Store last login / last access time in database
  • Move auth cache to MemCache

Profile Form

This form would allow user to change user data (including password) but only if user is authenticated. To implement profile form use:

Form::addTo($app)->setModel($app->auth->user);

Demos open profile form in a pop-up window, if you wish to do it, you can use this code:

Button::addTo($app, ['Profile', 'class.primary' => true])
    ->on('click', Modal::addTo($app)->set(function (View $p) {
        Form::addTo($p)->setModel($p->getApp()->auth->user);
    })->jsShow());

Things to try:

  • Ask user to verify old password before changing settings
  • Send SMS notification / email if any user setting has bees changed
  • Store user settings in multiple tables (join)

Password

Field 'password' is using a custom field class Password. Stored value is always a hash, use Password::hashPassword() + Password::set() methods to set the value or use Password::setPassword() method to set the password directly. You can use this field in any model like this:

$model->addField('password', [\Atk4\Data\Field\PasswordField::class]);

Also the password will not be stored in session cache and will not be accessible directly.

Things to try:

  • Add complexity validation
  • Add password recovery form
  • use CAPCHA when recovering password

Custom User Model

Although a basic User model is supplied, you can either extend it or use your own user model.

User Admin

We include a slightly extended "Admin" interface which includes page to see user details and change their password. To create admin page use:

\Atk4\Login\UserAdmin::addTo($app)
    ->setModel(new \Atk4\Login\Model\User($app->db));

Login

This uses a standard CRUD interface, enhancing it with additional actions:

  • key button allows to change user password and offers random password generator. Uses "input" field for a visible password. You can also use regular "edit" button which will contain asterisk-protected field for the password.
  • eye button is designed to show user details, such as which group he belongs to. Currently this panel and groups are not implemented.

Login

Things to try:

  • Add additional information on details modal.
  • Add audit log for user actions (login, change password etc)

Migrations

Use of migration is optional, but can help by populating initial structure of your user model. Look inside file demos/wizard.php. It simply adds a console component, which will execute migration of 'User' model.

When migration is executed it simply checks to make sure that table for 'user' exists and has all required fields. It will not delete or change existing fields or tables.

Roadmap

Generally we wish to keep this add-on clean, but very extensible, with various tutorials on how to implement various scenarios (noted above under "Things to try").

For some of those features we would like to add a better support in next releases:

  • [1.0] - add "$auth->check()" - for Automated authentication checks
  • [1.1] - add Password Reminder form and tutorial on integration with Email / SMS sending
  • [1.2] - add Password strength verification (and indicator)

If you would like to propose other features, please suggest them by opening ticket here:

login's People

Contributors

abbadon1334 avatar acicovic avatar darkside666 avatar fabulousgee avatar georgehristov avatar gowrav-vishwakarma avatar ibelar avatar karakal avatar mkrecek234 avatar mvorisek avatar philippgrashoff avatar romaninsh avatar webbird avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

login's Issues

Login not working with atk4 2.2

Calling atk4 login in atk4 2.2 via
$app->auth = $app->add([new \atk4\login\Auth()]);

results in "atk4\core\Exception: Seed class is not a subtype of static class "

Calling it via
$app->auth = $app->add(new \atk4\login\Auth()); // (without brackets - like we did it in previous version)

results in "atk4\core\Exception: Object is not an instance of static class "

Solutions?

Preference form not working

A fresh install on 2.2 or develop branch has the following issue - the user preference pane is not working. Javascript has the error "Can't find variable: $".

image

Verison 0.9

Admin:

  • We want to have admin panel. Should consist of user CRUD
  • + change password panel
  • + view user details (extensible)

Pages:

  • Login component (for a separate page)
  • Login controller (puts login component in virtual page)
  • Register component (can add text)
  • Forgot password component

Login Controller

  • authenticate user
  • logout user
  • session holding
  • force login as
  • verify password only
  • virtual page for login

Models:

  • User (includes basic field a user should have)
  • Admin (extends user)

Extras:

  • Password field (with encryption)

addHook/onHook issue - Most recent develop version breaks ACL code

After update today, this error occurs - I changed the addHook to onHook. Are there other refactoring implications that I missed?

Critical Error
TypeError : Argument 2 passed to atk4\data\Persistence::onHook() must be an instance of Closure or null, array given, called in /ATK4/crm/vendor/atk4/login/src/Auth.php on line 201

Finish automated mode

Currently you need to create login page, password reminder page etc.

This needs to be consolidated into virtual pages and displayed by the check method similar to ATK4.3.

$auth = $app->add(['Auth', 'reminder'=>true, 'register'=>true]);
$auth->setModel(new User($app->db));
$auth->check();

Cannot initialize Auth when DB field names do not match example User

It appears that if you setup your DB with field names different from the example User model, that is, initialize authentication like follows:

$app->add(new \atk4\login\Auth([
  'fieldLogin'=> 'user_name',
  'fieldPassword'=>'user_password',
  ]))
  ->setModel(new \atk4\login\Model\User($app->db));

Then it will fail in \atk4\login\Feature\setupUserModel() where field names are hardcoded to "name", "email', etc.

ACL docs are empty

There does not seem to be any documentation regarding ACL and how to use it. The respective md file in docs folder is empty.

Support for multiple user levels

Now we have a basic "is_admin" boolean condition but I think it's better to extend it in order to support multiple user levels with a vertical hierarchy (Admin, Moderator, Normal user) or separate groups (Admin, Customer, Supplier)

Sticky parameters lost after login

Steps to reproduce:

  • User opens a specific link unauthorized, e.g. customer.php?id=1234
  • Since unauthorized, login form is shown, and user authenticates
  • stickyGet parameters are lost then, resulting in a URL called customer.php

Desired behaviour:

  • stickyGet parameters survive authentication

Checked to be still an issue in most recent develop and 3.0 releases

Composer repo seems different from Github

Is it possible that Composer doesn‘t have the most actual version of atk4/login?
I have cleared the cache several times, deleted the repository manually etc.
I‘m using the dev-developer version of all repositories of atk4 (+add-ons).
I have seen all the recent changes when I inspected the closed PRs on Github.
But they seem to be missing when I download atk4/login through Composer.

That‘s really strange!

How do you manage your packages?
Is your Composer repo always the same as on Github?
Is the Git Hook to Packagist active?

Btw: I‘m on Mac OS 10.13.6

ACL creates heavy and slow database traffic

Steps to reproduce:

  • Have an application with more complex model structure (multiple hasOnes, hasManys)
  • Set-up just one rule and activate ACL by setACL();

Issue:

  • Database traffic is MASSIVE due to the login_access_rule queries
  • Even if you index the related Atk4/login tables properly, it makes a difference between 0.2 sec to 4 sec. in loading time for comparably simple scripts.

Cannot save adjusted User model

  • I created a custom User model (with additional fields) and initialized authentication and ACL in a project
  • I setup the automatic Preference page, so users can edit their data
  • Upon saving, I always end up in the login screen?

Why? When the User model is being saved, also a $model->reload(); is initiated in https://github.com/atk4/data/blob/e6c0cf59e190bc0093d20719f380c781742cfde0/src/Persistence/Sql.php#L608

A reload means, that the current entity is first unloaded. This then leads upon the next verification of the Role model in GetRules in ACL to force a login:

if (!$user->isLoaded()) {

At this point, entity is no longer loaded, but entityId is present.

I assume we can skip to force login here?

Custom login conditions

Need a demo (and docs) explaining how to provide user with a custom message, for example if his account was blocked.

Password field in 3.0 not working

Field password store the hash in property $passwordHash

in 2.4 - after load is still present in the field :
image

in 3.0 - after load is not present in the field :
image

I think it comes from here: https://github.com/atk4/data/blob/54cd831430139a2b6f8db72630272398abe301d8/src/Model.php#L1248

We copy only the data, the fields are reset losing any internal variables.

Conceptually is perfect, this is hot code and we must avoid any complex operations, but I think someone with a deeper knowledge of the recent @atk4/data development must take a look (@DarkSide666 @mvorisek @georgehristov) and decide to rewrite Password Field or Model load flow.

Add conditions to access rules

Feature request:
Allow rules to include certain conditions to be applicable, notably for example: make rule applicable if mode entity's field user_id is or is not identical to logged in user_id, pr entity carries a reference to a user group (which is allowed to edit only for example.

Currently commented out.

// Call $app->acl->can('admin'); for example to find out if user is allowed to admin things.

Preference Page not working if you extend User model with hasOne or hasMany fields

Scenario: Extended User model added in login demo project (file App.php) by
class UserNew extends \atk4\login\Model\User { function init(): void { parent::init(); $this->hasOne('team_id', [Team::class])->addTitle(); } }

where Team::class is a atk4\data\Model. The model is linked to Auth with the following code :
`` public function authenticate()
{
$this->auth = new \atk4\login\Auth(['check'=>true]);
$this->auth->app = $this;

    $m = new \atk4\login\demo\UserNew($this->db);

}`

If you open the user Preference page, then change a value and click Save, a Modal opens with the login form.
If you remove the line $this->hasOne('team_id', .... the form saves correctly.

The Team model added in App.php was
`class Team extends \atk4\data\Model {
public $table = 'team';

function init(): void
{
    parent::init();
    
    $this->addFields([
        'name','sort'
    ]);

}

}`

Workflow release-drafter.yml is using vulnerable action toolmantim/release-drafter

The workflow release-drafter.yml is referencing action toolmantim/release-drafter using references v5.6.1. However this reference is missing the commit 70eb821099dbcd875c2cba75dad4332d3cf5544d which may contain fix to the some vulnerability.
The vulnerability fix that is missing by actions version could be related to:
(1) CVE fix
(2) upgrade of vulnerable dependency
(3) fix to secret leak and others.
Please consider to update the reference to the action.

minimum stability in dev-develop branches should always require dev-develop branch of other atk repositories

"atk4/ui": "^1.5.7",

dev-develop branch should always point to other dev-develop branch or it get conflicts while developing on nightly build system

example:
Let's assume I am creating an application and since right-now a lot in development is going on in ui/data develop branches and these branches are my best option to include in my composer requirements.

Now, with dev-develop requirement of ui /schema and login, composer gets conflicts in minimum stability requirements.

So my requirements as follows

"minimum-stability": "dev",
"require": {
        "myapp/namespace":"dev-master",
        "atk4/ui": "dev-develop",
        "atk4/login": "dev-develop"
    },
    "require-dev": {
        "atk4/schema": "^1.1.1",   <= or even dev-develop both giving errors
        "phpunit/phpunit": "<6",
        "phpunit/phpcov": "^3.0",
        "codeclimate/php-test-reporter": "*",
        "behat/behat": "^3.4",
        "behat/mink-extension": "^2.2",
        "fzaninotto/faker": "*"
    }

never gets installed/updated with composer

Compatible with atk4/ui 5?

I can't for the life of me get atk4/login 3.1.0 installed with atk4/ui 5.0.0. It shows last commits were to update to latest atk4/ui version, but 3.1.0 refuses to allow ui/5. Am I missing something?

https://packagist.org/packages/atk4/login shows this as still requiring atk4/ui 3.1.0. Is this not up to date?

How to inject Auth0 service or integrate atk4/login with other AuthType?

I'm working on Auth0 integration and i have some clue about integration in atk4/login.

IMHO the actual atk4\login\Auth::check() method do too many things, not only check but even add UI elements and return an formatted error,

Did you think that can be space to extract an interface for login/logout/check? and use in place of the default one in case is injected in constructor?

What is Auth0 (https://auth0.com)

Auth0 can be used in API, Web Application and Mobile with a SSO, Single sign on, from multiple authentication provider like social or mail service.

Practically you call a login app url of Auth0, you login on an Auth0 customizable login page, and you get a response back like this :

$user_data =[
        'given_name' => null,
        'family_name' => null,
        'nickname' => null,
        'picture' => null,
        'locale' => null,
        'updated_at' => null,
        'email' => null,
        'email_verified' => null,
    ];

Email will be used as identifier for the user, other fields can be used to enrich user model without compiling again a form.

I used a Auth0ToModelMapper to map fields from $user_data to atk4\data\UserModel

In a classic Auth Interface i think the methods are usually :

  • check
  • login
  • getUser
  • logout

In Auth0 you can manage even roles and webhook.

Practically, you can delegate all the user process : authentication, creation, confirmation and recover to the Auth0 service.

Auth0 ha a free subscription which gives you 7000 active user and unlimited login per month.

You can integrate multiple App with the same Auth0 login.

Conclusion

here the gist of the working implementation : https://gist.github.com/abbadon1334/050260d1b117a86a8dcdfd0cbf4e3bcd

Sorry for the gist in place of a github repo, but Github Support still not answering me after 5 days.

It works, but i want to see when the ACL here will be finished and actions will be integrated from 2.0 release.

What do you think?

Demo from this addon do not work

Hi !

I try this addon using standard installation with 1.7.1 release atk/ui
using composer require atk/login
demos fail -> file ConfigTrait.php used in demos is not present in atk/core 1.7.1....

I also test this addon in standalone mode
composer could not resolve during update
"atk4/data": "dev-feature/action-fields as dev-develop"

action-fields not found in packages

I replace by dev-develop to resolve dependencies but finally ig get this error
admin-roles.php
atk4\core\Exception Unable to set property for the object
object:atk4\ui\CRUD ()
property:"formDefault"
value:{"0":"Form","layout":"Columns"}
9 | 64\www\login\vendor\atk4\ui\src\View.php: 274 | atk4\core\Exception | __construct

How to get a correct environnement using this addon ?

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.