Programmatically login admin in magento - login-script

i am new with magento, yet given the task to make custom api's with admin authentication. i am done with the api's but stucked in the admin authentication. the main problem i am facing is that: the passwords in magento are md5 encrypted and i dont know what to do with that. Help in this regard will be appriciated. my authentication code is below:
public function indexAction()
{
require_once 'app/Mage.php';
umask(0);
$app = Mage::app('default');
$array = $_GET;
$username = $_GET['username'];
$password = $_GET['password'];
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$user = Mage::getModel('admin/user')->loadByUsername($username); // user your admin username
$user_id = $user->getId();
// echo $user_id;
if(($user->getId())>=1)
{
echo "User Name: True";
echo "<br>";
$dbpassword = $user->getData('password');
// echo $dbpassword." ---- ";
// echo md5($username.$pass).":".$username;
// echo "<pre>";
// $a = Mage::helper('core')->validateHash($password, $dbpassword);
// print_r($a);
if($password == $dbpassword)
{
echo "<hr>";
echo "Password: True";echo "<br>";
echo "Authenticated :) Here we go!!";
}
else
{
echo "Password: False";
}
}
else
{
echo "User Name: False";
}
}

Use this function to validate your password against the magento hashed password
public function validateHash($password, $hash){
$hashArr = explode(':', $hash);
switch (count($hashArr)) {
case 1:
return md5($password) === $hash;
case 2:
return md5($hashArr[1] . $password) === $hashArr[0];
}
}
To check if the password is valid, do as below
if(validateHash($password, $user->getData('password'))){
echo 1;
}else{
echo 0;
}

Related

get_footer hook is calling twice in my wordpress plugin

I am new in wordpress development.
I made a plugin and inside it i am calling get_footer hook. But it is being called twice.
Here is my sample code.
function Show_Welcome_Message()
{
global $pagename;
if(is_user_logged_in())
{
$user = wp_get_current_user();
$user_name = ucwords($user->display_name);
setcookie("mcf_returning_user", $user_name, time() + (86400*30), "/");
}
if(!is_user_logged_in() && !empty($_COOKIE['mcf_returning_user']) && empty($_COOKIE['mcf_welcome_back_msg_later']))
{
if(!is_front_page())
{
echo "Not home";
$template_url = plugin_dir_path(__FILE__)."templates/prompt-message.php";
include $template_url;
setcookie("mcf_welcome_back_msg_later", "1", time() + 3600, "/");
}
else
{
echo "home";
}
}
}
add_action( 'get_footer', 'Show_Welcome_Message' );
Note :- Both 'home' and 'not home', both conditions are executing.
Try to changes the if condition
Replace this
if(!is_front_page())
with the below code
if(!is_home() && !is_front_page())

Is it possible to login wordpress admin dashboard with defined username and password?

Is there any way to login in wordpress admin dashboard with defined username and password for example
<?php
$username = 'my_username';
$password = 'my_password';
if ($_POST['username'] == $username && $_POST['password']){
echo "Valid credentials";
}else{
echo "Invalid credentials";
}
?>
Yes, that's possible, you can do like this by first checking if the creds are valid, then set up user cookies and log them in automatically:
$username = 'my_username';
$password = 'my_password';
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( !is_wp_error($user) ){
$user_id = $user->ID;
// Log the user in
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id );
// Perform any required redirections
wp_redirect( home_url() );
exit();
}else{
echo "Invalid credentials";
}
However, make sure that this runs before headers are send to work perfectly, you may hook it to template_redirects for example.

How avoid form resubmission on page refresh?

I'm doing a simple feedback form on WordPress. And like many people, I encountered the problem of resending the form when refresh the browser page. I know that this problem is solved through the use of the pattern "Post/Redirect/Get". Which says that you need after processing the data $_POST, request the same page using the $_GET method. But I can not use the result of the wp_mail function for redirection.
if(wp_mail($email, $email_subject, $email_message, $headers)) {
add_action('send_headers', 'simplemail_add_header');
}
function simplemail_add_header() {
header("Location: http://google.com");
}
It just does not work.
UPD
Here is my full code:
class SimpleMailer {
private $nonce = 'feedback_nonce';
public function __construct() {
add_action('phpmailer_init', array($this, 'simplemail_smtp_config'));
add_shortcode('simplemail', array($this, 'simplemail_sendmail'));
}
public function simplemail_smtp_config($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->SetFrom("admin#mail.com");
$phpmailer->addAddress("sender#mail.com");
$phpmailer->Host = "ssl://smtp.mail.com";
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = "admin#mail.com";
$phpmailer->Password = "password";
$phpmailer->SMTPSecure = 'ssl';
}
public function simplemail_sendmail($shortcode_attributes) {
global $wp;
$result = "";
$error = false;
$data = array();
$required_fields = array("feedback_name", "feedback_email", "feedback_message");
$atts = shortcode_atts(array(
"email" => get_bloginfo('admin_email'),
"form_action" => home_url($wp->request),
"form_cls" => '',
"mail_subject" => "Feedback message from",
"pls_name" => 'Your Name',
"pls_email" => 'Your E-mail Address',
"pls_message" => 'Your Message',
"label_submit" => 'Submit',
"error_common" => 'There was some mistake. Try again, a little later.',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks for your e-mail! We\'ll get back to you as soon as we can.'
), $shortcode_attributes);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$data[$field] = trim(strip_tags($value));
}
foreach ($required_fields as $required_field) {
$value = trim($data[$required_field]);
if(empty($value)) {
$error = true;
$result = $atts['error_empty'];
}
}
if(!empty($data["feedback_blank"])) {
$error = true;
$result = $atts['error_empty'];
}
if(!is_email($data['feedback_email'])) {
$error = true;
$result = $atts['error_noemail'];
}
if(!wp_verify_nonce($data[$this->nonce],'simplemail_nonce')) {
$error = true;
$result = $atts['error_common'];
}
if ($error == false) {
$email_subject = $atts['mail_subject']." [".get_bloginfo('name')."]";
$email_message = $data['feedback_message']."\n\n";
$headers = "From: ".$data['feedback_name']." <".$data['feedback_email'].">\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
if(wp_mail(null, $email_subject, $email_message, $headers)) {
add_action('send_headers', array($this, 'simplemail_add_header', 10, $atts['form_action']));
// wp_redirect( 'http://google.com', 301 );
// exit;
}
$data = array();
$result = $atts['success'];
}
}
return $this->simplemail_draw_form($atts, $data, $result);
}
public function simplemail_draw_form($atts, $data, $result) {
$output = "<form action='".$atts['form_action']."' class='".$atts['form_cls']."' method='post'>".PHP_EOL.
"<input type='text' name='feedback_name' placeholder='".$atts['pls_name']."' value='".#$data['feedback_name']."'>".PHP_EOL.
"<input type='text' name='feedback_blank'>".PHP_EOL.
"<input type='email' name='feedback_email' placeholder='".$atts['pls_email']."' value='".#$data['feedback_email']."'>".PHP_EOL.
"<textarea name='feedback_message' cols='30' rows='10' placeholder='".$atts['pls_message']."'>".#$data['feedback_message']."</textarea>".PHP_EOL;
$output .= wp_nonce_field('simplemail_nonce', $this->nonce, false);
$output .= ($result != "") ? '<div class="feedback-info">'.$result.'</div>' : '<div class="feedback-info"></div>';
$output .= "<button type='submit'>".$atts['label_submit']."</button>".PHP_EOL."</form>";
return $output;
}
public function simplemail_add_header($location) {
header("Location: {$location}");
}
}
$simplemailer = new SimpleMailer();
And I get this error if I uncomment the redirect. And nothing at all, if you try to use simplemail_add_header
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/nav-menu-template.php:256) in /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/pluggable.php on line 1216
I think you need to add a token in a hidden textbox and within the form to be submitted, the text in this text box will be the token and it need to change on every page load. Save this token in a session variable. Then add a condition at the top of the page to validate the token, if the token is different kill the loading process or display a message or whatever you feel is needed. You may also add token longevity to allow submitting of a page within certain amount of time.
The token creation, token validation and token longevity are normally a function somewhere that is called as needed and form different pages.
Edit:
If all you want is redirect the user to a different page then do:
if(mail succeed) {
header('location: thankyou.html');
}

Wordpress validation for title

Need to add blank and already exist validation for 'supports' => array( 'title') on my custom post type. But i dont want to use any plugin for this.
Thanks in advance.
add_action( 'admin_notices', 'custom_error_notice' );
function custom_error_notice(){
global $current_screen, $post;
if ( $current_screen->parent_base == 'edit' ){
if((!$post->post_name) && $_GET['post']) {
wp_redirect(admin_url('post-new.php?empty=1'));
}
if($_GET['empty']) echo '<div class="error"><p>Warning - Please fill up all fields correctly!</p></div>';
}
}
But this not working properly.
This may help you:-
add_action('save_post', 'album_save_post', 10, 2);
function album_save_post( $album_id, $album ) {
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || $album->post_type != 'music_album') return;
// echo '<pre>';
// print_r($album);
// echo '</pre>';
// die();
$errors = array();
// Validation filters
$title = $album->post_title;
if ( ! $title ) {
$errors['title'] = "The title is required";
}
// if we have errors lets setup some messages
if (! empty($errors)) {
// we must remove this action or it will loop for ever
remove_action('save_post', 'album_save_post');
// save the errors as option
update_option('album_errors', $errors);
// Change post from published to draft
$album->post_status = 'draft';
// update the post
wp_update_post( $album );
// we must add back this action
add_action('save_post', 'album_save_post');
// admin_notice is create by a $_GET['message'] with a number that wordpress uses to
// display the admin message so we will add a filter for replacing default admin message with a redirect
add_filter( 'redirect_post_location', 'album_post_redirect_filter' );
}
}
function album_post_redirect_filter( $location ) {
// remove $_GET['message']
$location = remove_query_arg( 'message', $location );
// add our new query sting
$location = add_query_arg( 'album', 'error', $location );
// return the location query string
return $location;
}
// Add new admin message
add_action( 'admin_notices', 'album_post_error_admin_message' );
function album_post_error_admin_message() {
if ( isset( $_GET['album'] ) && $_GET['album'] == 'error' ) {
// lets get the errors from the option album_errors
$errors = get_option('album_errors');
// now delete the option album errors
delete_option('album_errors');
$display = '<div id="notice" class="error"><ul>';
// Because we are storing as an array we should loop through them
foreach ( $errors as $error ) {
$display .= '<li>' . $error . '</li>';
}
$display .= '</ul></div>';
// finally echo out our display
echo $display;
// add some jQuery
?>
<script>
jQuery(function($) {
$("#title").css({"border": "1px solid red"})
});
</script>
<?php
}
}
i got the solution.
/** ADD Validation for title */
function force_post_title_init()
{
wp_enqueue_script('jquery');
}
function force_post_title()
{
echo "<script type='text/javascript'>\n";
echo "
jQuery('#publish').click(function(){
var testervar = jQuery('[id^=\"titlediv\"]')
.find('#title');
if (testervar.val().length < 1)
{
jQuery('[id^=\"titlediv\"]').css('border', '1px solid red');
alert('Post title is required');
return false;
}
});
";
echo "</script>\n";
}
add_action('admin_init', 'force_post_title_init');
add_action('edit_form_advanced', 'force_post_title');
// Add this row below to get the same functionality for page creations.
add_action('edit_page_form', 'force_post_title');
May be this also help for all of you.

Wordpress - Create own admin messages for Custom Post Type

I've created a custom post type called routes and I'd like to be able to return error messages to the screen when something goes wrong during a save/update e.g. The type allows for gpx/kml files to be uploaded and checked that the correct type has been posted. At the moment it just returns if it goes wrong - how can I set an error message?
//Return if file type wrong.
if($file_type != 'application/octet-stream' && $file_type != 'application/gpx+xml' ) {
return;
}
try this
example:
add_admin_message('Please enter valid URL for the project link', true);
add_admin_message('Your custom post type was updated');
source:
<?php
/**
* Messages with the default wordpress classes
*/
function showMessage($message, $errormsg = false)
{
if ($errormsg) {
echo '<div id="message" class="error">';
}
else {
echo '<div id="message" class="updated fade">';
}
echo "<p>$message</p></div>";
}
/**
* Display custom messages
*/
function show_admin_messages()
{
if(isset($_COOKIE['wp-admin-messages-normal'])) {
$messages = strtok($_COOKIE['wp-admin-messages-normal'], "##");
while ($messages !== false) {
showMessage($messages, true);
$messages = strtok("##");
}
setcookie('wp-admin-messages-normal', null);
}
if(isset($_COOKIE['wp-admin-messages-error'])) {
$messages = strtok($_COOKIE['wp-admin-messages-error'], "##");
while ($messages !== false) {
showMessage($messages, true);
$messages = strtok("##");
}
setcookie('wp-admin-messages-error', null);
}
}
/**
* Hook into admin notices
*/
add_action('admin_notices', 'show_admin_messages');
/**
* User Wrapper
*/
function add_admin_message($message, $error = false)
{
if(empty($message)) return false;
if($error) {
setcookie('wp-admin-messages-error', $_COOKIE['wp-admin-messages-error'] . '##' . $message, time()+60);
} else {
setcookie('wp-admin-messages-normal', $_COOKIE['wp-admin-messages-normal'] . '##' . $message, time()+60);
}
}

Resources