Social: Security token for chat and social wall

pull/3690/head^2
Angel Fernando Quiroz Campos 4 years ago committed by GitHub
parent 140f587099
commit c75b06adb8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 12
      main/inc/lib/chat.lib.php
  2. 12
      main/inc/lib/javascript/chat/js/chat.js
  3. 51
      main/inc/lib/security.lib.php
  4. 108
      main/inc/lib/social.lib.php
  5. 2
      main/social/home.php
  6. 2
      main/social/profile.php

@ -142,6 +142,7 @@ class Chat extends Model
'me' => get_lang('Me'),
'user_id' => api_get_user_id(),
'items' => $chats,
'sec_token' => Security::get_token('chat'),
];
echo json_encode($return);
@ -367,6 +368,13 @@ class Chat extends Model
) {
$relation = SocialManager::get_relation_between_contacts($fromUserId, $to_user_id);
if (!Security::check_token('post', null, 'chat')) {
if ($printResult) {
echo '0';
exit;
}
}
if (USER_RELATION_TYPE_FRIEND == $relation) {
$now = api_get_utc_datetime();
$user_info = api_get_user_info($to_user_id, true);
@ -405,8 +413,10 @@ class Chat extends Model
if (!empty($fromUserId) && !empty($to_user_id)) {
$messageId = $this->save($params);
if ($printResult) {
echo $messageId;
header('Content-Type: application/json');
echo json_encode(['id' => $messageId, 'sec_token' => Security::get_token('chat')]);
exit;
}
}

@ -39,6 +39,7 @@ var user_status = 0;
var widthBox = 320; // see css class .chatbox
//var ajax_url = 'chat.php'; // This variable is loaded in the template/layout/head.tpl file
var doubleCheck = '<span class="chatbox_checked"><i class="fa fa-check"></i><i class="fa fa-check"></i></span>';
var currentToken = '';
function set_user_status(status)
{
@ -134,6 +135,7 @@ function startChatSession()
dataType: "json",
success: function(data) {
if (data) {
currentToken = data.sec_token;
username = data.me;
currentUserId = data.user_id;
user_status = data.user_status;
@ -901,9 +903,11 @@ function checkChatBoxInputKey(event, chatboxtextarea, user_id)
if (message != '') {
$.post(ajax_url + "?action=sendchat", {
to: user_id,
message: message
message: message,
chat_sec_token: currentToken
}, function (messageId) {
if (messageId > 0) {
if (messageId.id > 0) {
currentToken = messageId.sec_token;
message = message.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
var item = {
from_user_info : {id: currentUserId, complete_name: 'me'},
@ -911,14 +915,14 @@ function checkChatBoxInputKey(event, chatboxtextarea, user_id)
date: moment().unix(),
f: currentUserId,
message: message,
id: messageId
id: messageId.id
};
createChatBubble(user_id, item);
$("#chatbox_" + user_id + " .chatboxcontent").scrollTop(
$("#chatbox_" + user_id + " .chatboxcontent")[0].scrollHeight
);
intervals[messageId] = setInterval(checkMessageStatus, chatHeartbeatTime, messageId);
intervals[messageId.id] = setInterval(checkMessageStatus, chatHeartbeatTime, messageId.id);
} else {
$("#chatbox_" + user_id + " .chatboxcontent").
append('<i class="fa fa-exclamation-triangle" aria-hidden="true"></i><br />');

@ -131,9 +131,11 @@ class Security
/**
* @return string
*/
public static function getTokenFromSession()
public static function getTokenFromSession(string $prefix = '')
{
return Session::read('sec_token');
$secTokenVariable = self::generateSecTokenVariable($prefix);
return Session::read($secTokenVariable);
}
/**
@ -144,24 +146,25 @@ class Security
*
* @return bool True if it's the right token, false otherwise
*/
public static function check_token($request_type = 'post', FormValidator $form = null)
public static function check_token($request_type = 'post', FormValidator $form = null, string $prefix = '')
{
$sessionToken = Session::read('sec_token');
$secTokenVariable = self::generateSecTokenVariable($prefix);
$sessionToken = Session::read($secTokenVariable);
switch ($request_type) {
case 'request':
if (!empty($sessionToken) && isset($_REQUEST['sec_token']) && $sessionToken === $_REQUEST['sec_token']) {
if (!empty($sessionToken) && isset($_REQUEST[$secTokenVariable]) && $sessionToken === $_REQUEST[$secTokenVariable]) {
return true;
}
return false;
case 'get':
if (!empty($sessionToken) && isset($_GET['sec_token']) && $sessionToken === $_GET['sec_token']) {
if (!empty($sessionToken) && isset($_GET[$secTokenVariable]) && $sessionToken === $_GET[$secTokenVariable]) {
return true;
}
return false;
case 'post':
if (!empty($sessionToken) && isset($_POST['sec_token']) && $sessionToken === $_POST['sec_token']) {
if (!empty($sessionToken) && isset($_POST[$secTokenVariable]) && $sessionToken === $_POST[$secTokenVariable]) {
return true;
}
@ -206,9 +209,11 @@ class Security
/**
* Clear the security token from the session.
*/
public static function clear_token()
public static function clear_token(string $prefix = '')
{
Session::erase('sec_token');
$secTokenVariable = self::generateSecTokenVariable($prefix);
Session::erase($secTokenVariable);
}
/**
@ -221,11 +226,12 @@ class Security
*
* @return string Hidden-type input ready to insert into a form
*/
public static function get_HTML_token()
public static function get_HTML_token(string $prefix = '')
{
$secTokenVariable = self::generateSecTokenVariable($prefix);
$token = md5(uniqid(rand(), true));
$string = '<input type="hidden" name="sec_token" value="'.$token.'" />';
Session::write('sec_token', $token);
$string = '<input type="hidden" name="'.$secTokenVariable.'" value="'.$token.'" />';
Session::write($secTokenVariable, $token);
return $string;
}
@ -240,10 +246,11 @@ class Security
*
* @return string Token
*/
public static function get_token()
public static function get_token($prefix = '')
{
$secTokenVariable = self::generateSecTokenVariable($prefix);
$token = md5(uniqid(rand(), true));
Session::write('sec_token', $token);
Session::write($secTokenVariable, $token);
return $token;
}
@ -251,13 +258,14 @@ class Security
/**
* @return string
*/
public static function get_existing_token()
public static function get_existing_token(string $prefix = '')
{
$token = Session::read('sec_token');
$secTokenVariable = self::generateSecTokenVariable($prefix);
$token = Session::read($secTokenVariable);
if (!empty($token)) {
return $token;
} else {
return self::get_token();
return self::get_token($prefix);
}
}
@ -584,4 +592,13 @@ class Security
return $output;
}
private static function generateSecTokenVariable(string $prefix = ''): string
{
if (empty($prefix)) {
return 'sec_token';
}
return $prefix.'_sec_token';
}
}

@ -2404,53 +2404,10 @@ class SocialManager extends UserManager
</script>';
}
/**
* @param string $urlForm
*
* @return string
*/
public static function getWallForm($urlForm)
public static function displayWallForm(string $urlForm): string
{
$userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
$form = new FormValidator(
'social_wall_main',
'post',
$urlForm.$userId,
null,
['enctype' => 'multipart/form-data'],
FormValidator::LAYOUT_HORIZONTAL
);
$socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
'SocialWallWhatAreYouThinkingAbout'
);
$form->addTextarea(
'social_wall_new_msg_main',
null,
[
'placeholder' => $socialWallPlaceholder,
'cols-size' => [1, 12, 1],
'aria-label' => $socialWallPlaceholder,
]
);
$form->addHtml('<div class="form-group">');
$form->addHtml('<div class="col-sm-6">');
$form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
$form->addHtml('</div>');
$form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
$form->addButtonSend(
get_lang('Post'),
'wall_post_button',
false,
[
'cols-size' => [1, 10, 1],
'custom' => true,
]
);
$form->addHtml('</div></div>');
$form->addHtml('</div>');
$form->addHidden('url_content', '');
$form = self::getWallForm($urlForm);
$form->protect();
return Display::panel($form->returnForm(), get_lang('SocialWall'));
}
@ -2989,12 +2946,19 @@ class SocialManager extends UserManager
{
$friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
$url = Security::remove_XSS($url);
$wallSocialAddPost = SocialManager::getWallForm(api_get_self());
if (!$wallSocialAddPost->validate()) {
return;
}
$values = $wallSocialAddPost->exportValues();
// Main post
if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
$messageContent = $_POST['social_wall_new_msg_main'];
if (!empty($values['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
$messageContent = $values['social_wall_new_msg_main'];
if (!empty($_POST['url_content'])) {
$messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
$messageContent = $values['social_wall_new_msg_main'].'<br /><br />'.$values['url_content'];
}
$messageId = self::sendWallMessage(
@ -3407,6 +3371,52 @@ class SocialManager extends UserManager
return $tabs;
}
private static function getWallForm(string $urlForm): FormValidator
{
$userId = isset($_GET['u']) ? '?u='.((int) $_GET['u']) : '';
$form = new FormValidator(
'social_wall_main',
'post',
$urlForm.$userId,
null,
['enctype' => 'multipart/form-data'],
FormValidator::LAYOUT_HORIZONTAL
);
$socialWallPlaceholder = isset($_GET['u'])
? get_lang('SocialWallWriteNewPostToFriend')
: get_lang('SocialWallWhatAreYouThinkingAbout');
$form->addTextarea(
'social_wall_new_msg_main',
null,
[
'placeholder' => $socialWallPlaceholder,
'cols-size' => [1, 12, 1],
'aria-label' => $socialWallPlaceholder,
]
);
$form->addHtml('<div class="form-group">');
$form->addHtml('<div class="col-sm-6">');
$form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
$form->addHtml('</div>');
$form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
$form->addButtonSend(
get_lang('Post'),
'wall_post_button',
false,
[
'cols-size' => [1, 10, 1],
'custom' => true,
]
);
$form->addHtml('</div></div>');
$form->addHtml('</div>');
$form->addHidden('url_content', '');
return $form;
}
/**
* Returns the formatted header message post.
*

@ -99,7 +99,7 @@ $social_group_block = SocialManager::getGroupBlock($user_id);
$friend_html = SocialManager::listMyFriendsBlock($user_id);
// Block Social Sessions
$wallSocialAddPost = SocialManager::getWallForm(api_get_self());
$wallSocialAddPost = SocialManager::displayWallForm(api_get_self());
$socialAutoExtendLink = SocialManager::getAutoExtendLink($user_id, $countPost);
$formSearch = new FormValidator(

@ -141,7 +141,7 @@ $sessionList = [];
// My friends
$friend_html = SocialManager::listMyFriendsBlock($user_id, $link_shared);
$addPostForm = SocialManager::getWallForm(api_get_self());
$addPostForm = SocialManager::displayWallForm(api_get_self());
$addPostFormPortfolio = SocialManager::getWallFormPortfolio(api_get_self());
$posts = SocialManager::getWallMessagesByUser($friendId);

Loading…
Cancel
Save