Codeigniter limit certain page elements to profile owner - function

I want to limit access to certain elements of a user's profile so that only the user can see them and not other logged in users. So far the is_logged_in function (see below) works fine, now I need to refine it so that it is limited to a specific user that is logged in.
I'm already including a user_id variable in my session data, so that's available for use.
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if($is_logged_in)
{
$this->index();
}
else
{
redirect('fooview');
}
}

you will need to know the user_id of the profile you are viewing, lets assume in your controller you have it as $user_id.
in your controller you can do $is_owner = $this->session->userdata('user_id') == $user_id ? true : false;
then pass it to your view as e.g. $is_owner.
then in your view simply have
if($is_owner){
//show stuff
} else {
//message saying stuff is private!
}

Related

How to change language automatically using user browser language Yii2?

A user can change the language manually from the website. But for better user experience, I would like to change it automatically based on the users' browser language. I have a global Controller and can use init() and then redirect.
Please give me tips to do it right.
You should remember the chosen language for a user, if they had selected one previously, I store this in the database, in a user_preference table.
Then you need to intercept the request, it can be done in the application configuration file, using the on beforeRequest property.
If you don't have stored a preference for the current user, or the user is a guest, use the browser language to set the application language.
Configuration file
use app\models\User;
...
'on beforeRequest' => function ($event) {
$user_lang = '';
if (!Yii::$app->user->isGuest) {
// Check if you have stored a language preference for the user
$user_lang = User::findIdentity(Yii::$app->user->id)->getUserPreference('lang');
}
if (!empty($user_lang)) {
// If you have a stored preference for the user, use it
Yii::$app->language = $user_lang;
} else {
// If you don't have a preference, use the browser language
// Get the browser language from the headers
$browser_lang = Yii::$app->request->headers->get('accept-language');
// Alternatively get the headers from the event
// $event->sender->request->headers->get('accept-language')
// Calculate the language you want to provide based on the browser language
$language_code = LanguageHelper::calculatei18nCode($browser_lang);
Yii::$app->language = $language_code;
}
},
...
If you wanted to keep your configuration file clean, you could use filters instead to intercept the request.
Your LanguageHelper::calculatei18nCode($browser_lang) method would try to find a match for the browser language in the available languages, if it didn't find one it could return the closest match, or the default application language.
LanguageHelper
public static function calculatei18nCode ($browser_lang) {
// For example, if you are offering one translation file for french
if (stripos($browser_lang, 'fr')) {
return 'fr';
}
...
return 'en';
}

Twitter: Why statuses/user_timeline.json returns an empty array?

I want to view another user's timeline and I'm wondering why user_timeline.json returns an empty array? When I don't put parameters it works fine, it shows the authenticated user timeline but I can't see other users timeline when I put the user_id as a parameter. Why?
Here's my code:
getUserTimeline: function(id_str) {
var endpoint_url = CONSTANTS.BASE_URL + 'statuses/user_timeline.json';
createTwitterSignatureParams('GET', endpoint_url, 'user_id', id_str);
return $resource(endpoint_url).get({'user_id': id_str}).$promise;
},
Problem solved!
Just had to change GET by QUERY
$resource(endpoint_url).get(...) ==> $resource(endpoint_url).query(...)

Block access to pages in cakePHP

How do I block access to any page in cakePHP. With page, I'm referring to actual views lying in the Page folder.
When I remove this line in, it works, but it also stops users from logging in. It would create a direct loop:
$this->Auth->allow('display');
Basically, when a user wants to view any page, and they are not logged in, they will be redirected to the login (app/users/login) page. After they've logged in, they will be directed to the page they last tried to access.
How would I go about this?
The problem in your situation is that all pages shown by the pagesController are the same action (display()), only using a different parameter (the page to display). You can therefore not block access to the display action, because that will block access to all pages.
If the number of pages is limited, then the easiest way to implement this is ControllerAuthorize. Read the documentation here; Using ControllerAuthorize
class AppController extends Controller {
public $components = array(
'Auth' => array('authorize' => 'Controller'),
);
public function isAuthorized($user = null) {
// Make all actions public
return true;
}
}
Then, inside your pages controller;
class PagesController extends AppController {
public function isAuthorized($user = null) {
if ('display' !== $this->request->action) {
// other actions; let he AppController handle access
return parent::isAuthorized($user);
}
if (!empty($user)) {
// Logged-in users have access to any page
return true;
}
$page = empty($this->request->params['pass'][0]) ? null : $this->request->params['pass'][0];
switch($page) {
case 'home':
case 'about':
// etc
return true;
}
// all other pages are 'private'
return false;
}
}
Just an example, of course, modify to fit your needs
use
$this->Auth->allow('\','display');
it allow all after '\' pages..
or
if you not allow except display page you do nothing.

Best way to trigger a Modal View Controller on Tab Bar press.

When the user triggers a tabbar item I want to display present a modal view controller.
I have something working but it's probably not the cleanest way to do it. It also prevents the UITabBarItem to be in selected state.
What I did is setting this method to false and in the that method body presenting the view controller (via the RootViewController).
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
UINavigationController *nvc = (UINavigationController*)viewController;
Do you guys have any idea of a cleaner implementation of this that would allow the TabBarItem to be highlighted ?
This is the one of the way to use the MVC on Tab bar...To highlighting the tab bar item like that.
id currentlySelected; //This will hold the address of the selected view
id dontAllowSelection; //This will hold the address of the Denied view
(BOOL)tabBarController:(UITabBarController *)tabBarControllers shouldSelectViewController:(UIViewController *)viewController
{
if (dontAllowSelection != nil && //If it is nil, we will skip it.
dontAllowSelection == viewController) //If the selected view is Denied return NO
{
return NO;
}
currentlySelected = viewController;
if (currentlySelected == someViewIWantToDisableOtherFor) //Any logic can go here to enable the Denied View.
{
dontAllowSelection = anotherViewIWantDisabled; //Set my denied view.
}
else
{
dontAllowSelection = nil; //Unsed the Denial.
}
return YES;
}

taking values separately using local storage in html5

I am making an app in html5.It is like a quiz based app. I am randomly fetching questions from the XML and displaying it one by one.I am using page navigation for that. After completing and submitting your answer u will switch to other page.if once i submit my answer i cannot attempt it back. but i can see the feedback and score on switching to that page that is my problem. I have display that feedback and score and to store it in local storage. i am able to do local storage but values that i am getting is overriding. so i am getting last submitted value.Now my concern is to divide that values navigation number wise.right now what is happening if i submit my answer and suppose i am at navigation number 3 n i am looking at navigation part 1 then there also i am getting last submitted value not the part 1 value.Please give ur suggestion and help me out for that.
Here is the code snippet:
//for navigation of pages
$(document).ready(function (){
/*$(document).bind("contextmenu",function(e){
return false;
});*/
var obj;
total=x.length;
for(var j=0;j<x.length;j++)
{
if(j==0)
{
$("#navigationlist").append('<li>'+(j+1)+'</li>');
display_nav(j,$("#selected_link"))
}
else
$("#navigationlist").append('<li>'+(j+1)+'</li>');
}
$("#next").bind("click",function (){
$(".navg").each(function(index){
if($(".navg").length==(i+1))
{
if(index==0)
obj=$(this);
}
else
{
if(index==(i+1))
obj=$(this);
}
});
for(var j=0;j<xmlDoc.getElementsByTagName("question").length;j++)
{
xmlDoc.getElementsByTagName("question")[j].removeAttribute("status");
}
$("#btnSubmit").attr("disabled","false");
$("#btnSubmit").attr("onclick","checekAnswer()");
display_nav(0,obj)
}
else
display_nav((i+1),obj)
});
});
and
correctAnswers++;
localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
$("#feedback").append(score[0].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
}
else
{
//var val = [];
//val.push(feedback[0].childNodes[0].nodeValue);
//localstorage.setItem('feedback', JSON.stringify(val));
//localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
//alert(localStorage.getItem("feedback"));
/*var v={"test":feedback[0].childNodes[0].nodeValue};
localStorage.setItem('feedback',v);
alert(localStorage.getItem('feedback'));*/
scores1.push(feedback[0].childNodes[0].nodeValue);
localStorage.setItem("highscores",JSON.stringify(scores1));
var scores = localStorage.getItem("highscores");
alert(scores);
scores = JSON.parse(scores);
alert(scores[0]);
$("#feedback").html(score[1].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
$("#feedback").append("hello");
}
//$("#counter").html("left="+xPos+",top="+yPos);
$("#trFeedBack").show("slow");
display_nav(j,obj)
}
} // end function
If I understand your question, your problem is to store items with same name but related to different pages.
LocalStorage being defined by domain, and not by page, you must change the keys you use. The usual solution is to prefix the names you want.
For example :
localStorage['pages.12.feedback'] = "the feedback I'm giving related to page 12";
localStorage['global.feedback'] = "the feedback I'm giving related to the global site";
(you'll notice I use the short notation, that I find more readable that using setItem)