I am trying to implement an email verification after registering an account. So after registering an account, an email will be sent to the user email to verify. the email was sent using the email class of codeigniter.
The code for sending the email is as below
$config['wordwrap'] = TRUE;
$this->email->initialize($config);
$this->email->from('admin#mathplication.com', 'admin');
$this->email->to($user_email);
$this->email->subject('Registration verification for mathplication');
$this->email->message('
Thanks for signing up!
Your account has been created, you can login with the following credentials
after you have activated your account by pressing the url below.
Please click this link to activate your account:
<a href='.base_url('verify').'?email='.$user_email.'&rand='.$user_rand.'>Click Here</a>');
$this->email->send();
and in the routes.php in the config folder
$route['verify'] = "login_register/view_verify
in which view_verify is the function in my login_register controller
inside this view_verify I will check the two parameters I passed which are the email and the random string generated.
function view_verify($email,$rand)
{
//$email = $this->input->get('email');
//$rand = $this->input->get('rand');
$this->load->database();
$this->load->model('login_model');
$result= $this->login_model->email_verification($email,$rand);
if($result==TRUE)
{
$this->load->view('pages/verify');
}
}
I will get a 404 page not found error. Not sure if my routing with the variables is the problem here or not or is there another way of passing parameters through url to the controller. Thanks in advance for the help.
If you are going to be using query strings in the url, you will need to enable that in the config. Possible there might also be issues with permitted_uri_chars because of the email address.
You could generate the url with the user id and nonce like:
<a href='.base_url('verify').$user_id.'/'.$user_rand.'>Click Here</a>');
Which should produce something like
http://www.example.com/verify/1234/23q23rq2rq24rq34rq34rq34r
Then in routes:
$route['verify/(:any)'] = "login_register/view_verify/$1";
At this point the function view_verify should work correctly exactly as it is now except you will need to adjust your model to do the lookup via user id instead of by email.
function verify($verificationText=NULL){
$noRecords = $this->HomeModel->verifyEmailAddress($verificationText);
if ($noRecords > 0){
$error = array( 'success' => "Email Verified Successfully!");
}else{
$error = array( 'error' => "Sorry Unable to Verify Your Email!");
}
$data['errormsg'] = $error;
$this->load->view('index.php', $data);
}
Related
i am working on laravel socialite to login using gmail.i can able to store user info and if gmail id and email already exist then it should redirect to dashboard.
public function googleCallback()
{
$user = Socialite::with('google')->user();
$email=$user->email;
$user_id=$user->id;
if(Auth::attempt(['email' =>$email,'password'=>$user_id]))
{
//return redirect('user/UserDashboard');
//return Redirect::to('user/UserDashboard');
echo "i am here";
}
}
in the above code if i use echo then it will print .suppose if redirect to dashboard it wont work.i don't know why redirect wont work for socialite.Can anyone tell where i am doing wrong ?
thank you
Update:
suppose if i login to my site using gmail or fb or github then data will store in my db.if that person login second time then it should redirect to user dashboard. the above code will check if auth::attempt exist or not.suppose if i print any think in inside if() block it works.suppose if i add redirect to dashboard then login through gmail and all not working
I don't know till what extent my answer would be correct but it should go somewhat like this:
public function googleCallback()
{
$user = Socialite::with('google')->user();
$email=$user->email;
$user_id=$user->id;
$user_db = \App\User::where('email', $user->email)->first();
if (count($user_db) == 1) {
echo "i am here";
} else {
// Your registration process
// With Login process i.e. auth()->attempt(YOURDATA);
}
}
This is the only way that I could have done this thing. If anything else I can help in, put it in the comment box.
use this to redirect
return redirect()->intended('user/UserDashboard');
I've posted this question twice in the last two days and I have really run dry of solutions. I'm creating a very simple comment box that when filled out sends the comment in an email to my company's safety department. I have been receiving this 5.5.4 Invalid Domain Error for the last couple days.
It's SMTP and TLS. The port and server name is correct. The server allows for anonymous emails, and does not validate. I'm using the Swiftmailer library so I shouldn't need to script a ELHO/HELO. The only property of the email that's not defined/hard coded is the body of the message. This is the code for my controller (index.php).
// Initialize Swiftmailer Library
require_once("./swiftmailer/lib/swift_required.php");
// Class that contains the information of the email that will be sent (from, to, etc.)
require_once("./classes/EmailParts.php");
// The class that "breaks" the data sent with the HTML form to a more "usable" format.
require_once("./classes/ContactForm.php");
// =====================
// Main Configuration
// =====================
define("EMAIL_SUBJECT", "Safety Concerns");
define("EMAIL_TO", "safetydepartment#company.com");
define("EMAIL_FROM", "safetydepartment#company.com");
// SMTP Configuration
define("SMTP_SERVER", 'exchange.company.local');
define("SMTP_PORT", 25);
function main($contactForm) {
// Checks if something was sent to the contact form, if not, do nothing
if (!$contactForm->isDataSent()) {
return;
}
// Validates the contact form and checks for errors
$contactForm->validate();
$errors = array();
// If the contact form is not valid:
if (!$contactForm->isValid()) {
// gets the error in the array $errors
$errors = $contactForm->getErrors();
} else {
// If the contact form is valid:
try {
// send the email created with the contact form
$result = sendEmail($contactForm);
// after the email is sent, redirect and "die".
// We redirect to prevent refreshing the page which would resend the form
header("Location: ./success.php");
die();
} catch (Exception $e) {
// an error occured while sending the email.
// Log the error and add an error message to display to the user.
error_log('An error happened while sending email contact form: ' . $e->getMessage());
$errors['oops'] = 'Ooops! an error occured while sending your email! Please try again later!';
}
}
return $errors;
}
// Sends the email based on the information contained in the contact form
function sendEmail($contactForm) {
// Email part will create the email information needed to send an email based on
// what was inserted inside the contact form
$emailParts = new EmailParts($contactForm);
// This is the part where we initialize Swiftmailer with
// all the info initialized by the EmailParts class
$emailMessage = Swift_Message::newInstance()
->setSubject($emailParts->getSubject())
->setFrom($emailParts->getFrom())
->setTo($emailParts->getTo())
->setBody($emailParts->getBodyMessage());
// Another Swiftmailer configuration..
$transport = Swift_SmtpTransport::newInstance(SMTP_SERVER, SMTP_PORT, 'tls');
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($emailMessage);
return $result;
}
// Initialize the ContactForm with the information of the form and the possible uploaded file.
$contactForm = new ContactForm($_POST, $_FILES);
// Call the "main" method. It will return a list of errors.
$errors = main($contactForm);
// Call the "contactForm" view to display the HTML contact form.
require_once("./views/contactForm.php");
I've posted the entirety of my code at Dropbox. There's not much, but I think the problem must lie in the Index.
i use tank auth as login handler in code igniter. when i use the forget password feature, i get a link send by mail http://xx.xx.xx/en//auth/reset_password/2/01b951fd2a02efa2d64f1fe70c2a4e3b. When i click this link it always says: "Your activation key is incorrect or expired. Please check your email again and follow the instructions."
i changed the segments so it gets the right segments but somehow it the goes wrong on if ($this->form_validation->run()). it Somehow wants the new_password and confirm_new_password as post data but from the link in the email no post data will ofcourse be sent.
Is this a bug in tank auth, is there a quickfix (does tank_auth forget a step, is something not configured right?)
reference code:
function reset_password()
{
$break =$this->uri->total_segments();
$new_pass_key= $this->uri->segment($break);
$user_id= $this->uri->segment($break-1);
$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean|matches[new_password]');
$data['errors'] = array();
if ($this->form_validation->run()) { //breaks here. For some reason wants to validate post data which
if (!is_null($data = $this->tank_auth->reset_password($user_id, $new_pass_key,$this->form_validation->set_value('new_password')))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
// Send email with new password
$this->_send_email('reset_password', $data['email'], $data);
$this->_show_message($this->lang->line('auth_message_new_password_activated').' '.anchor('/auth/login/', 'Login'));
} else { // fail
$this->_show_message($this->lang->line('auth_message_new_password_failed'));
}
} else {
// Try to activate user by password key (if not activated yet)
if ($this->config->item('email_activation', 'tank_auth')) {
$this->tank_auth->activate_user($user_id, $new_pass_key, FALSE);
}
if (!$this->tank_auth->can_reset_password($user_id, $new_pass_key)) {
$this->_show_message($this->lang->line('auth_message_new_password_failed'));
}
}
$this->load->view('auth/reset_password_form', $data);
}
Your new_pass_key and $user_id are wrong I guess.
It should work out of the box with this:
$user_id = $this->uri->segment(3);
$new_pass_key = $this->uri->segment(4);
EDIT:
$user_id = $this->uri->segment(4);
$new_pass_key = $this->uri->segment(5);
Why did you change that by the way?
I am building a social network via code igniter. Upon registration, the potential member get's stored in the db, and their status get's marked to pending. I then send them a confirmation email with a hashed token link. When they hit the link it marks their account as active and takes them to a welcome page that has a sign in.
When I go to the link it sets of an infinite loop and freezes my computer when I'm working on my MAMP. ( or I'm suspicious that it's an infinite loop )
Here is my pertinent code:
auth CONTROLLER that sends the email:
function varification_email()
{
$query = $this->db->query('SELECT * FROM users order by id desc LIMIT 1');
$token = sha1($user->email.$user->salt).dechex($user->id);
$domain = "clci.dev/index.php";
$link = "http://www.".$domain."/account/confirmation/?token=$token";
foreach ($query->result() as $user)
{
$this->load->library('email');
$this->email->from('noreply#cysticlife.org', 'CysticLife');
$this->email->to($user->email);
$this->email->subject('Welcome to CysticLife!');
$this->email->message("Thanks for signing up for CysticLife! To complete the registration process please go to the following web address:\n\n$link\n\n-Your friends at CysticLife\n\nPlease remember to add the cysticlife.org domain to your address book to ensure that you receive your CysticLife e-Notifications as requested.eh");
$this->email->send();
}
account CONTROLLER that the user is linked back to from the email:
public function confirmation() {
$data['main_content'] = 'account/confirmation';
$this->load->view('includes/templates/main_page_template', $data);
$this->load->library('encrypt');
$this->load->helper('url');
$this->load->library('session');
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login) {
$user = $this->um->validate(array('email' => $this->input->post('email')));
if( $user ) {
// CHECK THE USER'S PASSWORD AGAINST THE ONE FROM THE LOGIN FORM
if($user->password == $this->encrypt->sha1( $user->salt . $this->encrypt->sha1($this->input->post('password')))) {
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata(array(
'email' => $this->input->post('email')
));
$this->session->userdata('logged_in');
redirect('account/dashboard');
exit;
}
}
}
$this->index();
}
Thanks in advance
varification_email()
In varification_email(), $user is used before it is defined. I assume the real code doesn't have this issue.
Your method for selecting the user in the DB in prone to concurrency errors (wrong user returned).
confirmation()
I already had encountered browser hangs because of too large cookies, exceeding something like 4 kB. Have a look at that.
The problem might be in user_model->validate(). Comment out the following of the code and check if it works.
How can I verify an email address with codeigniter? I just went through the manual, I couldn't find this.
With email verification, i mean the exact same verification you see when registering on a community forum.
Thanks in advance!
Use the Email Class to send the email. The email could contain a link with a "secret key", something random and hash-like, like 5dfg7898ssdf (I made that one up :) ). The link could point to: example.com/verify/user/5dfg7898ssdf Then in a codeigniter controller called "verify", you put this function (just some quick code):
function user($key = NULL)
{
if($key)
{
// Find key in database
// If it exists, then mark
// the corresponding user as "activated"
}
}
function verify($verificationText=NULL){
$noRecords = $this->HomeModel->verifyEmailAddress($verificationText);
if ($noRecords > 0){
$error = array( 'success' => "Email Verified Successfully!");
}else{
$error = array( 'error' => "Sorry Unable to Verify Your Email!");
}
$data['errormsg'] = $error;
$this->load->view('index.php', $data);
}