pwFoo

FrontendUser: login, logout and register users / members

Recommended Posts

FrontendUser uses a temp PW User object. All existing fields should be saved, but it's done via PW api, not the PW admin create user process (haven't looked into it...).

Send email after user registration? You could write a plugin hook after FrontendUser save() method...

    /**
     * Save the temp User object
     * @param User $user Temp User object to save
     * @return boolean Sucessful (true) saved or not (false)
     */
    protected function ___save($user) {
        if (empty($user->name) || empty($user->email) || $user->pass->hash == '') {
            return $this->_('Register process unexpected failed!');
        }
        if ($user->save()) {
            return true;
        }
        return $this->_('User registration failed!');
    }

Hook after save() method. If return value  === true (exactly true! not "== true") you can send a mail via PW api or load a module to send the email...

  • Like 1

Share this post


Link to post
Share on other sites

Thats actually my code. It works for register but dont work for the Email new user. 

Ive thought i could write i plugin hook but i cant :D

So please help where is the mistake ? 

$fu = $modules->get('FrontendUser');

// prepare login form (default parameters)
$fu->login();

// Default parameter
//$fu->login(array('username', 'password'));

// Additional LoginPersist and ProcessForgotPassword module integration (built-in)
$fu->login(array('username', 'password',  'forgot'));

// process login / form submit
$fu->process('../objekte/');

// output form
echo $fu->render();


$modules->get('EmailAdminNewUser'); // lade Modul um den Admin zu benachrichtigen 
$u_vorname = $modules->get('InputfieldText');
$u_vorname->label = $this->_('Vorname');
$u_vorname->attr('id+name', 'u_vorname');
$u_vorname->required = 1;
$u_vorname->fhSanitizer = 'text';

$nachname = $modules->get('InputfieldText');
$nachname->label = $this->_('Nachname');
$nachname->attr('id+name', 'nachname');
$nachname->required = 1;
$nachname->fhSanitizer = 'text';

$unternehmen = $modules->get('InputfieldText');
$unternehmen->label = $this->_('Unternehmen');
$unternehmen->attr('id+name', 'unternehmen');
$unternehmen->required = 1;
$unternehmen->fhSanitizer = 'text';

$strnr = $modules->get('InputfieldText');
$strnr->label = $this->_('Strasse / Hausnummer');
$strnr->attr('id+name', 'strnr');
$strnr->required = 1;
$strnr->fhSanitizer = 'text';

$plz = $modules->get('InputfieldText');
$plz->label = $this->_('Plz / Ort');
$plz->attr('id+name', 'plz');
$plz->required = 1;
$plz->fhSanitizer = 'text';

$tel = $modules->get('InputfieldText');
$tel->label = $this->_('Telefonnummer');
$tel->attr('id+name', 'tel');
$tel->required = 1;
$tel->fhSanitizer = 'text';

$fu->addHookBefore('save', function($event) {
    $form = wire('fu')->form;
    $user = wire('fu')->userObj;
    $user->addRole('registered');

    if(!count($form->getErrors())) {

        wire('fu')->userObj->u_vorname = $form->fhValue('u_vorname', 'text');
        wire('fu')->userObj->u_nachname = $form->fhValue('nachname', 'text');
        wire('fu')->userObj->u_unternehmen = $form->fhValue('unternehmen', 'text');
        wire('fu')->userObj->u_hausnummer = $form->fhValue('strnr', 'text');
        wire('fu')->userObj->u_plzort = $form->fhValue('plz', 'text');
        wire('fu')->userObj->u_telefonnummer = $form->fhValue('tel', 'text');

    
    }
});


// prepare register form
$fu->register();
$fu->register(array('username',  $u_vorname, $nachname, $unternehmen , $strnr, $plz, $tel, 'email', 'password'));
$fu->process('/');
echo $fu->render();

The admin need an email with new user details and a link to activate this user. 

Because there are 3 different view gropus of users. 

Where i put the code for my custom email to the user admin ? 

I tried to understand it with the after hooks but how to hook the press on the registeration button ? 

Thanks 

PS: I have some problems with the forget user funktion. I see it twice ? 

if im logged in i see blank place. can i set a message like you are logged in currently ? 

Share this post


Link to post
Share on other sites

Hi,

$modules->get('EmailAdminNewUser'); // lade Modul um den Admin zu benachrichtigen 

I haven't used or seen EmailAdminNewUser before. So I don't know how it should work / triggered...

    public function init() {
        if($this->data['generatePassword']){
            $this->addHookBefore('InputfieldPassword::render', $this, 'notRequiredNote');
            $this->addHookBefore('InputfieldPassword::processInput', $this, 'removeRequired');
        }
        if(wire('page')->process == "ProcessUser") $this->addHookAfter('ProcessPageEdit::buildFormContent', $this, 'addEmailFields');
        $this->addHookAfter('Password::setPass', $this, 'getPassword');
        $this->pages->addHookBefore('saveReady', $this, 'sendNewUserEmail');
    }

FrontendUser "save()" method won't trigger it I think...

EmailAdminNewUser will only work if it hooks into $user->save().

Share this post


Link to post
Share on other sites

hmm but it doesent relly work for me still ? 

why ? 

The testmail works but the Module not really.

 

Share this post


Link to post
Share on other sites

hmm but it doesent relly work for me still ? 

why ? 

The testmail works but the Module not really.

Try putting $modules->get('EmailAdminNewUser');

After

$fu = $modules->get('FrontendUser');

At least that is how I have it.

Do you have this in site/config.php:

/**
* adminEmail: address to send optional fatal error notifications to.
*
*/
$config->adminEmail = 'name@exampledomain.com';

Because my module is getting the email with

wire('config')->adminEmail

I did notice that I didn't even have that config set, but it still always worked for me..

Share this post


Link to post
Share on other sites

I haven't take a look into it, but add hooks have to be done before $fu->process(). After this method the form is processed by PW.

Why not send the email by wireMail() with custom content and recipient?

$mail = wireMail();
$mail->to($adminEmail);
$mail->subject($subject);

// html body
//$mail->bodyHTML($emailContentHtml);

// plain body
$mail->body($emailContentPlain);

$mail->send();

Could be done hooked after FrontendUser::save.

  • Like 1

Share this post


Link to post
Share on other sites

I haven't take a look into it, but add hooks have to be done before $fu->process(). After this method the form is processed by PW.

Why not send the email by wireMail() with custom content and recipient?

$mail = wireMail();
$mail->to($adminEmail);
$mail->subject($subject);

// html body
//$mail->bodyHTML($emailContentHtml);

// plain body
$mail->body($emailContentPlain);

$mail->send();

Could be done hooked after FrontendUser::save.

Thanks heaps! Now I can throw away my silly little module made in a hurry.

Here is a solution that will email to all your superusers, thanks to LostKobrakai for being there on IRC to give advice:

  $form->addHookAfter('FrontendUser::save', function() use($fu, $input) {
    $superusers = wire('users')->find("roles=superuser");
    $emails = $superusers->explode('email');
    $subject = "A new user registered at the site: " . $fu->userObj->fullname;
    $emailContentPlain = "Go and activate them: http://www.mysite.fi/myadmin/";
    $mail = wireMail();
    $mail->to($emails);
    $mail->from('admin@mysite.fi');
    $mail->subject($subject);

    // plain body
    $mail->body($emailContentPlain);

    $mail->send();
  });
 
  $fu->process($redirectDestination);

Note: wire('pages')->find("template=user.. did not work. It had to be wire('users') !!

$fu->userObj->fullname; is getting the value of my extra field, fullname.

  • Like 1

Share this post


Link to post
Share on other sites

Hey there pwFoo this is great! Great module you wrote here. I am working on implementing it into my site and was wondering if I am misunderstanding how to set up registration with email validation. The flow that I am used to on the net is :

register with information - > submit

see splash screen that reminds the user to check their email to confirm

follow email link -> enable account (sometimes this is the step where the user sets a permanent password if none is entered on the sign up form)

redirect to profile page for more information on the user 

How would you recommend that I go about implementing this module in order to accomplish this? 

Share this post


Link to post
Share on other sites

Take a look at the FrontendUserRegisterEmailValidation submodule. It adds an email validation step before the new user will be registered.

Just load the plugin as additional field "emailValidation".

$fu->register(array('username', 'email', 'emailValidation', 'password'));
  • Like 1

Share this post


Link to post
Share on other sites

Apologies for not being more specific. I set the option for email validation and have noticed that the email contains a validation token. Is there any way to implement a flow that allows for a user to follow the link using the token instead of first having to enter the code that was emailed. I would like to just have the user follow the link to the password reset page where they would then enter their own password. Then on reset the user would be automatically logged in. 

Share this post


Link to post
Share on other sites

The Email should contain the token and a link to the second step of user registration form (filled with username, email address and token).

Password reset isn't handled by FrontendUser module, it just uses the ProcessForgotPassword core module.

Your use case is possible and the needed snippets and examples should be here in the forum, but you need to extend FrontendUser to work as you want it. I implemented ProcessForgotPassword because it should be secure and do the password reset job.

  • Like 1

Share this post


Link to post
Share on other sites

Sorry, I wasn't intending to sound critical  :). I just didn't want to start modifying anything before I fully understood the intended behaviour of the module. I now have it implemented and the css is now in place. I have one issue though. When registering you first input your username and your email. When you click to send the code the form posts back as it should, but then the error gets tripped before the whole form has been submitted "Email validation code NOT match!". I think I could locate a fix in the code but I was wondering if this is something that you were planning on dealing with in your own code before I go hacking at the module.

Share this post


Link to post
Share on other sites

It was important to check token mismatch and changed / duplicate username or email address before a new user is saved.

I think you shouldn't use my plugin. Write a submodule which isn't based on FrontendUserRegisterEmailValidation.

Just register an unpublished user. Send an activation mail via hook after save(). User activation could be done as independent (sub-)module.

Share this post


Link to post
Share on other sites

FrontendUser is based on the PW form api and PW inputfields.

Haven't links here, but just search the forum.

https://processwire.com/talk/topic/9467-add-a-css-class-to-an-inputfield-on-render/

https://processwire.com/talk/topic/2089-create-simple-forms-using-api/

I hope that will help you to style your form.

If someone build a base / example style I'll add it to the module / documentation.

  • Like 2

Share this post


Link to post
Share on other sites

Get it to work only with css. Thank you for your links.

How can i change the placeholders inside the textfields? It says username, password and login.

How could i translate that?

Share this post


Link to post
Share on other sites

Get it to work only with css. Thank you for your links.

How can i change the placeholders inside the textfields? It says username, password and login.

How could i translate that?

In PW settings - languages - your lang - select file for translation and give the module file.

  • Like 1

Share this post


Link to post
Share on other sites

In PW settings - languages - your lang - select file for translation and give the module file.

This was new to me. Thank you very much! :frantics:

Share this post


Link to post
Share on other sites

I have some Redirect Issues on Logout in Firefox. When I press Logout in Chrome everything seems working. In FF ive got endless redirects. The way I lougout is:

$fu = $modules->get('FrontendUser');
$fu->logout();

Runs on an own page, means not on the same where the Login/Register is located (There is only a Link to the Logout Page to print a feedback message). Whats the fault? I dont use redirect because I dont need any. 

By the way: I find no elegant way to send an email, when some new user is registrated. Is there any way to send an email out of the box from this module? Every extern way means to send emails in a very general way without events fired directly from my registration form.

Share this post


Link to post
Share on other sites

Easiest way to deal with logging out is to just make a two line template at /logout/

<?php
     if($user->isLoggedin()) $session->logout();
     $session->redirect($pages->get('/')->url);
?>

Share this post


Link to post
Share on other sites

Easiest way to deal with logging out is to just make a two line template at /logout/

<?php
     if($user->isLoggedin()) $session->logout();
     $session->redirect($pages->get('/')->url);
?>

We take a look at the modules logout() method ;)

    public function ___logout ($redirect) {
        $this->session->logout();
        $this->session->redirect($redirect, false);
    }

So just do what you want in the template.

With the redirect above and the modules logout method it looks like that.

// logout the current user
$fu->logout($pages->get('/')->url);

If you use a combined login / logout page or a redirect to the current page you need if / else in the template like that.

if ($user->isGuest()) {
    // do login or just write a "You're logged out..." message 
}
else {
    // do logout
}

I could add a check to prevent a loop, but with a redirect to the current page you have to handle it with if / else to serve the correct page for guests / loggedin users...

Edited by pwFoo
  • Like 2

Share this post


Link to post
Share on other sites

Thank you a lot. I think it would be enough to mention this in your documentation. I was really confused about the endless loop redirects.

And is there any ability to send mails? Because I have the problem that any redirect is looses the data from posting the form. It would be helpful to send the admin an email that a new user is registered.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Mike Rockett
      As I mentioned in this issue, I've create a new textformatter for ParsedownExtraPlugin, which adds some oomph to your markdown.
      Repo: Parsedown Extra Plugin
      Unlike the built-in textformatter for Parsedown and Parsedown Extra, this should be used when you want to use Extra with additional configuration/customisation.
      Some examples:
      ### Test {.heading} - A [external link](https://google.com/){.google} with `google` as a class that opens in a new tab if the config property is set. - [Another link](/page){target=_blank} that opens in a new tab even though it isn't external. ```html .html <p>Test</p> ``` There's some config options available to you, such as setting attributes on all/external images and links, setting table and table-cell alignment classes, adjusting footnote classes and IDs, adding <code> attributes to their parent <pre> elements, and changing the <code> class if your syntax highlighter does not use language-*.
      I was thinking about adding the ability to make links open in a new tab by appending a plus to the link syntax, but only external links should be opening in a new tab anyway. Further, this would add extra, unnecessary processing time.
      Please let me know if you bump into any problems. ☺️
    • By Mike Rockett
      TextformatterTypographer (0.4.0 Beta)
      A ProcessWire wrapper for the awesome PHP Typography class, originally authored by KINGdesk LLC and enhanced by Peter Putzer in wp-Typography. Like Smartypants, it supercharges text fields with enhanced typography and typesetting, such as smart quotations, hyphenation in 59 languages, ellipses, copyright-, trade-, and service-marks, math symbols, and more.
      Learn more on my blog
      It's based on the PHP-Typography library found over at wp-Typography, which is more frequently updated and feature rich that its original by KINGdesk LLC.
      The module itself is fully configurable. I haven't done extensive testing, but there is nothing complex about this, and so I only envisage a typographical bug here and there, if any.
      Please do test it out and let me know what you think.
      Also note that I have indicated support for PW 2.8, but I haven't tested there as yet. This was built on PW 3.0.42/62.
    • By Mike Rockett
      Jumplinks for ProcessWire
      Release: 1.5.50
      Jumplinks is an enhanced version of the original ProcessRedirects by Antti Peisa.
      The Process module manages your permanent and temporary redirects (we'll call these "jumplinks" from now on, unless in reference to redirects from another module), useful for when you're migrating over to ProcessWire from another system/platform. Each jumplink supports wildcards, shortening the time needed to create them.
      Unlike similar modules for other platforms, wildcards in Jumplinks are much easier to work with, as Regular Expressions are not fully exposed. Instead, parameters wrapped in curly braces are used - these are described in the documentation.
      Under Development: 2.0, to be powered by FastRoute
      As of version 1.5.0, Jumplinks requires at least ProcessWire 2.6.1 to run.
      View on GitLab
      Download via the Modules Directory
      Read the docs
      Features
      The most prominent features include:
      Basic jumplinks (from one fixed route to another) Parameter-based wildcards with "Smart" equivalents Mapping Collections (for converting ID-based routes to their named-equivalents without the need to create multiple jumplinks) Destination Selectors (for finding and redirecting to pages containing legacy location information) Timed Activation (activate and/or deactivate jumplinks at specific times) 404-Monitor (for creating jumplinks based on 404 hits) Additionally, the following features may come in handy:
      Stale jumplink management Legacy domain support for slow migrations An importer (from CSV or ProcessRedirects) Feedback & Feature Requests
      I’d love to know what you think of this module. Please provide some feedback on the module as a whole, or even regarding smaller things that make it whole. Also, please feel free to submit feature requests and their use-cases.
      Note: Features requested so far have been added to the to-do list, and will be added to 2.0, and not the current dev/master branches.
      Open Source

      Jumplinks is an open-source project, and is free to use. In fact, Jumplinks will always be open-source, and will always remain free to use. Forever. If you would like to support the development of Jumplinks, please consider making a small donation via PayPal.
      Enjoy! 
    • By bernhard
      Some of you might have followed the development of this module here: https://processwire.com/talk/topic/15524-previewdiscussion-rockdatatables/ . It is the successor of "RockDataTables" and requires RockFinder to get the data for the grid easily and efficiently. It uses the open source part of agGrid for grid rendering.
       
      WHY?
      ProcessWire is awesome for creating all kinds of custom backend applications, but where it is not so awesome in my opinion is when it comes to listing this data. Of course we have the built in page lister and we have ListerPro, but none of that solutions is capable of properly displaying large amounts of data, for example lists of revenues, aggregations, quick and easy sorts by the user, instant filter and those kind of features. RockGrid to the rescue 😉 
       
      Features/Highlights:
      100k+ rows Instant (client side) filter, search, sort (different sort based on data type, eg "lower/greater than" for numbers, "contains" for strings) extendable via plugins (available plugins at the moment: fullscreen, csv export, reload, batch-processing of data, column sum/statistics, row selection) all the agGrid features (cell renderers, cell styling, pagination, column grouping etc) vanilla javascript, backend and frontend support (though not all plugins are working on the frontend yet and I don't plan to support it as long as I don't need it myself)  
      Limitations:
      While there is an option to retrieve data via AJAX the actual processing of the grid (displaying, filtering, sorting) is done on the client side, meaning that you can get into troubles when handling really large datasets of several thousands of rows. agGrid should be one of the most performant grid options in the world (see the official example page with a 100k row example) and does a lot to prevent problems (such as virtual row rendering), but you should always have this limitation in mind as this is a major difference to the available lister options that do not have this limitation.
      Currently it only supports AdminThemeUikit and I don't plan to support any other admin theme.
       
      Download: https://gitlab.com/baumrock/FieldtypeRockGrid
      Installation: https://gitlab.com/baumrock/RockGrid/wikis/Installation
      Quikckstart: https://gitlab.com/baumrock/RockGrid/wikis/quickstart
      Further instructions: https://gitlab.com/baumrock/RockGrid/wikis/quickstart#further-instructions
      German Translation File: site--modules--fieldtyperockgrid--fieldtyperockgrid-module-php.json
      Changelog: https://gitlab.com/baumrock/FieldtypeRockGrid/raw/master/changelog.md
       
      Module status: alpha, License: MIT
      Note that every installation and uninstallation sends an anonymous google analytics event to my google analytics account. If you don't want that feel free to remove the appropriate lines of code before installation/uninstallation.
       
      Contribute:
      You can contribute to the development of this and other modules or just say thank you by
      testing, reporting issues and making PRs at gitlab liking this post buying me a drink: paypal.me/baumrock/5 liking my facebook page: facebook.com/baumrock hiring me for pw work: baumrock.com  
      Support: Please note that this module might not be as easy and plug&play as many other modules. It needs a good understanding of agGrid (and JavaScript in general) and it likely needs some looks into the code to get all the options. Please understand that I can not provide free support for every request here in the forum. I try to answer all questions that might also help others or that might improve the module but for individual requests I offer paid support for 60€ per hour (excl vat).
       
      Use Cases / Examples:
      Colored grid cells, Icons, Links etc. The Grid also has a "batcher" feature built in that helps communicating with the server via AJAX and managing resource intensive tasks in batches:

      Filters, PW panel links and instant reload on panel close:

      You can combine the grid with a chart library like I did with the (outdated) RockDataTables module:

    • By thomasaull
      Some time ago I created a site profile for creation of a REST API with ProcessWire. Since I kept struggeling with updating stuff between different projects which use this, I decided to convert it into a module. It is now ready for testing: https://github.com/thomasaull/RestApi
      Additionally I added a few small features:
      automatic creation of JWT Secret at module install routes can be flagged as auth: false, which makes them publicly accessible even though JWT Auth is activated in module settings To check things out, download and install the module and check the folder /site/api for examples.
      If you find any bugs or can think of improvements, please let me know!