$this->params['prefix'] is detected only if $_SESSION values exists - session

At the moment I'm using Cakephp...
This webpage contains an admin section and a "normal" section... you can access to the admin section using "...site/admin".
If the user writes in the url "...site/admin" then it's suppossed to be redirected to an admin logon section...
However, if he tries to go to the "site" directly, then he will also be redirected to another logon section but for access to the normal site.
The problem is... my code is not working... if I try to access to the admin site, then I'm redirected to the normal logon section and I must write my credentials... then after that, I'm able to go to the admin site (and prompted for admin credentials, which is ok)
If all of this sounds confusing, you have to know that:
Administrator section -> needs admin credentials
Normal section -> needs normal credentials
but this is what's happening right now:
Administrator section -> needs admin credentials -> needs normal credentials
This is the code, it's located on AppController (the program heads directly to redirect(site.com) and I don't understand why)
function beforeFilter()
{
session_start();
if($this->params['prefix'] == 'admin'){ //Si se quiere ir a la sección de admin...
if($this->Session->check('Admin.logged')){ //si esta logueado...
$this->layout = 'admin'; //Pone el layout de admin
}else{ //Si no esta logeado un admin...
$this->redirect(array('controller'=>'info','action'=>'login','admin'=>false)); //lo redirige al login.
}
}
else //si no está en admin, está en todas las demás páginas, a las cuales no debería poder entrar si no está logueado...
{
//si le ponés test=true te deja entrar igual y te llena los valores de sesión, esto es más que nada para poder hacer las pruebas de forma local...
$value = $this->request->query('test');
if (isset($value))
{
$_SESSION['web']['nombre'] = 'John';
$_SESSION['web']['apellido'] = 'Doe';
}
if(!isset($_SESSION['web']['nombre']))
$this->redirect('http://www.thesite.com.ar');
}
}
It basically doesn't detect I'm using the prefix "admin" UNTIL I have logged with normal (test) credentials (they are written automatically if you do "site?test")
I hope this is clear...

Related

Can I use drawables in Wear OS Tiles?

I'm going through the Tiles Codelab:
https://developer.android.com/codelabs/wear-tiles
I want to use drawables instead of url in the tile layout.
i replace the url with drawable (for example: "R.drawable.ic_search_24")
but i see a blank circle. What is happening?
In the MessagingTileRender.kt (module)
private fun contactLayout(
context: Context,
contact: Contact,
clickable: ModifiersBuilders.Clickable,
) = Button.Builder(context, clickable)
.setContentDescription(contact.name)
.apply {
if (contact.avatarUrl != null) {
//se c'è un link recupera l'immagine
setImageContent(R.drawable.ic_search_24.toString())
//setImageContent(contact.imageResourceId())
//mettere qui il recupero dell'immagine
} else {
setTextContent(contact.initials)
//altrimenti prende le iniziali e li mette colorate come bottone
setButtonColors(ButtonColors.secondaryButtonColors(MessagingTileTheme.colors))
}
}
.build()
thanks for trying the codelab.
Tiles can't use drawables directly like this. In your layout, it's necessary to pass a string ID (it's not a url).
In onResourcesRequested() (or similar), you must map that ID to an ImageResource (which can be created from a drawable), as in the codelab.
Check out the finished module for an example.

How do I set the Icon of the RemoteNotification in GeneXus 15

I've been trying to set an icon for a RemoteNotification, but always get this error when I send it (I'm using log4net):
System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada. ---> System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto.
em GeneXus.Utils.GXDbFile.PathToUrl(String path)
em GeneXus.Programs.aenvianotificacaodispositivo.S121()
em GeneXus.Programs.aenvianotificacaodispositivo.executePrivate()
em GeneXus.Programs.aenvianotificacaodispositivo.execute()
I couldn't find any example in the wiki or in the forums. That's my code:
//commented also didn't work
//&Image.FromUrl('http://www.example.com/my_app_icon.png')
//&Image.FromUrl(app_icon_notif.Link())
&Image.FromImage(app_icon_notif)
&RemoteNotification.Icon = &Image
&RemoteNotification.Message = &NotificMensagem
&RemoteNotification.Event.Name = 'Notas'
&RemoteNotification.Event.Execution = EventExecution.OnLauchByUser
&Notifications.Add(&RemoteNotification)
What am I missing? I'm on GeneXus 15 U2 C#. Thank you
The notification icon is set by the Android Notification Icon property of the main object.
The corresponding imagen needs to follow some considerations mentioned here

How to display an error message in Xamarin PCL

I'm doing a simple try/catch (in a PCL project) to validate the users connection to the app, but I cant seem to find the DisplayAlert() method used in the Xamarin websites example.
Here are my usings:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Security;
using System.Diagnostics;
Here is the code:
public async Task Connexion()
{
// on met en place un try catch pour déceler toute erreur dans la procédure de connexion
try
{
// url de récupération du json de l'acteur
string urlActeur = "http://10.0.0.5/ppe3JoJuAd/gsbAppliFraisV2/webservices/w_visiteur.php" + "?" + "login=" + Login + "&" + "pass=" + Pass;
//instanciation du client http qui envoi un header json
HttpClient clientActeur = new HttpClient();
clientActeur.DefaultRequestHeaders.Accept.Clear();
clientActeur.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//réponse à la requête Http
var response = await clientActeur.GetAsync(urlActeur);
var json = response.Content.ReadAsStringAsync().Result;
var acteurJson = JsonConvert.DeserializeObject<ActeurJson>(json);
//on vérifie les informations de connexion du user (ici cela se ait avec oldMdp car pas d'implémentation du SHA1 actuellement en Xamarin, auquel cas nous auions converti le contenu du champ pass en sha1 puis vérification avec le champ mdp de l'acteur)
if (acteurJson.Acteur.login == login && acteurJson.Acteur.mdp == acteurJson.Acteur.oldMdp)
App.Current.MainPage = new VisitePage();
}
catch
{
await DisplayAlert()//intelisense does not find the using or the required dll
}
where should I look or what should I do to display the message ?
You shouldn't do a DisplayAlert from a Task. You should relay a message back to the calling class about a failure or just raise the exception to the calling class. For a task to come back into the UI and raise a message is bad.
Also your use of HttpClient is off. HttpClient is meant to be used as a singleton method. Try and create one per project or modules as a static singleton.
All that being said, try this:
public class ConnexionHelper
{
public async Task Connexion()
{
try
{
System.Diagnostics.Debug.WriteLine("trying stuff");
}
catch( Exception ex )
{
Xamarin.Forms.Page ourPage = App.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
if (ourPage != null)
{
await ourPage.DisplayAlert("eeek", "error has occurrred", "not ok");
}
}
}
Application.Current.MainPage.DisplayAlert should works
Its better to add userdialogs plugin for xamarin. It comes up with different type of alerts,toasts etc for showing messages in the UI. Also it gives a better UI.
You can install the userdialogs from https://www.nuget.org/packages/Acr.UserDialogs/
After installing, you can show alert as follows:
UserDialogs.Instance.Alert("","","OK">);
You can also display alert as toasts.
You can display toast message using Toasts.Forms.Plugin
Setup
In your iOS, Android, WinRT and UWP projects please call:
DependencyService.Register<ToastNotification>(); // Register your dependency
ToastNotification.Init();
// If you are using Android you must pass through the activity
ToastNotification.Init(this);
If you are using Xamarin Forms, you must do this AFTER your call to Xamarin.Forms.Init();
Permissions
In iOS you must request permission to show local notifications first since it is a user interrupting action.
// Request Permissions
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// Request Permissions
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>
{
// Do something if needed
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null);
app.RegisterUserNotificationSettings(notificationSettings);
}
Usage
Use dependency service in order to resolve IToastNotificator.
var notificator = DependencyService.Get<IToastNotificator>();
var options = new NotificationOptions()
{
Title = "Title",
Description = "Description"
};
var result = await notificator.Notify(options);
The result that is returned is a NotificationResult with an Action inside with one of the following values.
[Flags]
public enum NotificationAction
{
Timeout = 1, // Hides by itself
Clicked = 2, // User clicked on notification
Dismissed = 4, // User manually dismissed notification
ApplicationHidden = 8, // Application went to background
Failed = 16 // When failed to display the toast
}
If you want the Clicked NotificationAction you must set IsClickable = true in the NotificationOptions.

Bot Framework Formflow EnumSelectOne template doesn't work on telegram

I'm facing a problem using FormFlow feature.
My model has the propertie below:
[Describe("Site")]
[Template(TemplateUsage.EnumSelectOne, "Em qual {&} será feita a reserva? {||}", ChoiceStyle = ChoiceStyleOptions.Default]
[Template(TemplateUsage.NotUnderstood, "Não entendi sua resposta... você precisa me informar o nome de um site válido ou ainda pode clicar num dos botões acima")]
public Site? Site { get; set; }
Site is a enum, and it renders a list of buttons. It works properly on webchat but not in Telegram.
When the user select an option in webchat, the answer is prompted below and the bot continue the dialog. However, in telegram, the user select an option and the answer is not prompted on the chat and the framework stay waiting a user interaction.
Can anyone help me with this issue?
Tks in advance.
I solved the question... To work properly on telegram you need to put ChoiceStyle = ChoiceStyleOptions.Auto on Template attribute.
Here the whole property configuration:
[Describe("Tipo de solicitante")]
[Template(TemplateUsage.EnumSelectOne, "Que {&} você é? {||}", ChoiceStyle = ChoiceStyleOptions.Auto)]
[Template(TemplateUsage.NotUnderstood, "Não entendi sua resposta... você precisa me informar se é funcionário ou terceiro ou ainda pode clicar num dos botões acima")]
public TipoSolicitante? TipoSolicitante { get; set; }

Logins got crossed in CakePHP 2

I have one huge problem here:
In a CakePHP project, I have a double-step login, where users log-in against the company's Active Directory, and after successful check of credentials, they are checked again on a DB so only specific people can enter the site. The problem is that recently, users can see another user's info as if they entered with another person's credentials. Worst of all is that not in all sections have the same login. Sometimes person A can see himself on page1, but on page2 he can see himself as B, and in page3 he sees himself as C.
But the weirdest of all is that this is not the only project that happens. It appears on another project as well, whom shares the same specs, and the custom Authenticate component (but it crosses only with the own project's users)
I'm a bit lost here, as I checked the cookies sent (only the cake session id) and they are ok and match the session file.
So, any clues what can be the problem here? I don't even know where to begin to look. Could it be on Auth? Or Session? Or Cache?
The platform specs:
PHP 5.3
Cakephp 2.5 (not 100% sure but it's around 2.4 and 2.6)
IIS7
SQL Server 2014 DB
EDIT
Here's my custom authenticate method. Please don't worry about the bad coding of this method, as I had to get it working ASAP (will fix it soon).
public function authenticate(CakeRequest $request, CakeResponse $response)
{
CakeSession::delete('AuthError');
if($request->data['Usuario']['login'] == '' || $request->data['Usuario']['contraseña'] == '')
{
CakeSession::write('AuthError', __("Usuario o contraseña inválidos"));
return false;
}
$datasource = ConnectionManager::getDataSource('active_directory');
$dominio = isset($request->data['Usuario']['dominio']) ? strtoupper($request->data['Usuario']['dominio']) : 'INTERNAL';
$host = strtolower($request->data['Usuario']['dominio']).'.'.$datasource->config['host']; //imsglobal.com
$port = $datasource->config['port'];
$enlace = ldap_connect($host, $port);
$check = #ldap_bind($enlace,$dominio."\\".$request->data['Usuario']['login'],$request->data['Usuario']['contraseña']);
// debug($check);
ldap_close($enlace);
if($check)
{
$this->UsuarioModel = ClassRegistry::init('Usuario');
$usuario = $this->UsuarioModel->obtener_usuarios(array('LOGIN' => $request->data['Usuario']['login']));
if(!empty($usuario))
{
return array('id' => $usuario[0]['id'], 'usuario' => $usuario[0]['usuario']);
}
else
{
CakeSession::write('AuthError', __("El usuario ingresado no se encuentra registrado en el sistema. Por favor contacte a un administrador"));
}
}
else
{
CakeSession::write('AuthError', __("Usuario o contraseña inválidos"));
}
return false;
}

Resources