Trying to update OR insert in Symfony2 controller with a form - forms

What's wrong in my code ? I want to update or insert an Moteur object depending on url.
Thanks by advance.
/**
* #Route("/moteur/{moteurid}", name="moteur", requirements={"moteurid" = "\d+"}, defaults={"moteurid" = null})
* #Template()
*
* Cette page permet d'enregistrer de nouveaux moteurs (et de les éditer).
*/
public function moteurAction($moteurid)
{
$args=array();
$avertissement = null;
if (!$this->get('security.context')->isGranted('ROLE_ADMIN'))
{
$avertissement = "Vous n'avez pas le droit d'accéder à cet espace.";
return $this->redirect($this->generateUrl('index', array('avertissement' => $avertissement)));
}
$args['menu']['admin'] = 'selected';
$obj = null;
if ($moteurid == null)
{
$obj = new Moteur();
}
else
{
$obj = $this->getDoctrine()->getRepository('CreasixtineAFBundle:Moteur')->find($moteurid);
}
$form = $this->createForm(new FormMoteur(), $obj);
$args['form'] = $form->createView();
if ($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if ($form->isValid())
{
$obj = $form->getData(); // Type Moteur()
$pn = $obj->getPnid();
$em = $this->getDoctrine()->getEntityManager();
if ($moteurid == null)
{
$em->persist($obj);
$avertissement = "Moteur créé !";
}
else
{
// Rien, le moteur sera mis à jour avec flush()
$avertissement = "Moteur mis à jour !";
}
foreach ($pn as $my_pn){$em->persist($my_pn);}
$em->flush();
return $this->redirect($this->generateUrl('admin', array('avertissement' => $avertissement)));
}
else
{
throw new Exception("Le formulaire n'est pas valide.");
}
}
$contenu = $this->rendu($args, "formulaire_moteur.html.twig");
return $contenu;
}

First, you don't need this line as PHP5 natively passes object by reference :
$obj = $form->getData(); // Type Moteur()
Then, your relation between Moteur and Pn is a bit confusing. You get a Pn with getPnid() but you get an object you wanna persist ?
Anyway, these Pn objects should be persisted before Moteur, so here is what I would write :
if ($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$pn = $obj->getPnid();
//Persist these related objects BEFORE Moteur
foreach ($pn as $my_pn)
{
$em->persist($my_pn);
}
if ($moteurid == null)
{
$em->persist($obj);
$avertissement = "Moteur créé !";
}
else
{
// Rien, le moteur sera mis à jour avec flush()
$avertissement = "Moteur mis à jour !";
}
$em->flush();
return $this->redirect($this->generateUrl('admin', array('avertissement' => $avertissement)));
}
else
{
throw new Exception("Le formulaire n'est pas valide.");
}

Related

typo3 remove session data of fe-user

Hi I have an typo3 extension that stores data in session.
After my actions are finished I want to remove the session data.
I tried this:
$GLOBALS['TSFE']->fe_user->removeSessionData();
But this does not work.
What is my fail? Thanks in advance
UPDATE
if ( is_null($GLOBALS["TSFE"]->fe_user->getKey("ses", "Step1")) ) {
$this->redirect('noProductFound');
}
$arguments = $this->request->getArguments();
$reloadPage = new \TYPO3\ShopExtension\Controller\ShopStep();
$product = $arguments['product'];
$orderProcessed = $GLOBALS['TSFE']->fe_user->getKey('ses', 'orderProcessed');
#Verhindern das Seite neu geladen wird und eine neue Bestellung getätigt wird.
if ($reloadPage->getReload() == true | $orderProcessed == true) {
$this->redirect('noProductFound', null, null, array('error' => 'orderProcessed'));
} else {
if ($product == ShopConstant::AG_TRIAL) {
$this->save_Product_Trial();
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} elseif ($product == ShopConstant::AG_PROFESSIONELL || $product == ShopConstant::AG_PREMIUM || $product == ShopConstant::AG_ULTIMATE) {
$afterOrderOrderId = $this->save_Product_Auditgarant($product);
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} elseif ($product == ShopConstant::BOOK_AL || $product == ShopConstant::BOOK_PH || $product == ShopConstant::BOOK_CPMS || $product == ShopConstant::BOOK_USABILITY) {
$this->save_Product_Book($product);
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} elseif ($product == ShopConstant::INSTITUTSTAG || $product == ShopConstant::INSTITUTSTAG_PARTNER || $product == ShopConstant::INSTITUTSTAG_ALUMNI) {
$this->save_Product_Institutstag($product);
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} else {
$this->redirect('noProductFound');
}
#Session löschen, da Daten ab hier nicht mehr benötigt werden.
$GLOBALS['TSFE']->fe_user->removeSessionData();
$GLOBALS['TSFE']->fe_user->setKey('ses', 'Step1', null);
$GLOBALS['TSFE']->storeSessionData();
// \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($GLOBALS['TSFE']);
// exit();
#Führt einen redirect durch mit angehängtem Attribut des letzten Step.
$this->redirect('getContent', null, null, array(
'step' => $arguments['lastStep'],
'shopStep' => $arguments['product'],
'afterOrderOrderId' => $afterOrderOrderId
));
In case you did $GLOBALS['TSFE']->fe_user->setAndSaveSessionData('session_key', $somevalue); you can simply do $GLOBALS['TSFE']->fe_user->setAndSaveSessionData('session_key', null); to delete the session data.

How I check if the user is an ADMIN

Hello guys
I'm trying to create a function that allows the user to connect as admin, or simple user by creating a column in the users table called (is_adminn) as INT.
for the moment i'm doing it in a static way :
function _check_admin_login($username, $pword)
{
$target_username="firas";
$target_pass="password";
if(($username==$target_username) && ($pword==$target_pass)){
return TRUE;
}else{
return FALSE;
}
}
and then i will call it in the admin controller :
function username_check($str){
$this->load->module('store_accounts');
$this->load->module('site_security');
$error_msg = "Vous avez saisi un nom d'utilisateur ou un mot de passe incorrecte";
$pword = $this->input->post('pword', TRUE);
$result = $this->site_security->_check_admin_login($str, $pword);
if($result==FALSE){
$this->form_validation->set_message('username_check', $error_msg);
return FALSE;
}else{
return TRUE;
}
}
I did many tests like if the value of is_adminn is equal to 1 , it returns True
function _check_admin_login($username, $pword)
{
$this->load->module('store_accounts');
$this->store_accounts->fetch_data_from_db();
$is_adminn = $data['is_adminn'];
if($is_adminn==1){
return TRUE;
}else{
return FALSE;
}
}
It's easy to do what you want, first time check if the username and the password matches and after that check is the user id have the status is_admin 1.
model
public function check_admin($id){
$query = $this->db->get_where('user', array('id' => $id, 'is_admin' => 1 ));
if ($query->num_rows()>0) {
return true;
}else{
return false;
}
}
controller
$data['temp'] = $this->User_model->get_id_by_email($data['login']['email']);
$data['user'] = $this->User_model->check_login($data['login']['email'], $data['login']['password']);
if ($data['user'] && $this->Admin_model->check_admin($data['temp'][0]['id'])) {
$session_data = array(
//what you wanna store in session
);

org.apache.shiro.UnavailableSecurityManagerException

I have a big problem on my project. I have looked everywhere in internet but nothing was found. So this is my Bean:
#Named(value = "loginBean")
#SessionScoped
public class LoginBean implements Serializable {
#EJB
private RoleServiceLocal rsbl;
#EJB
private ProfilServiceLocal psbl;
#EJB
private UtilisateurServiceLocal usbl;
private String username;
private String password;
private String newPass;
private String retapPass;
private String lastPass;
private String us = "";
private String per = "";
private String question;
private String recupResponse = "";
private String reponse;
private String creerDoleance, modifierDoleance,
creerficheExec, modifierficheExec, creerRapportTest, modifierRapportTest, fiche, direction, creerDirection, modifierDirection,
creerProduit, modifierProduit, creerClient, modifierClient, creerVersion, modifierVersion, technicien, creerTechnicien, modifierTechnicien,
creerMAJ, modifierMAJ, MAJ, doleance, ficheExec, RapportTest, produit, client, version, technique, creerTechnique, modifierTechnique,
profil, creerProfil, modifierProfil, associerProfil, associerRole, activerCompte, desactiverCompte, securite, administration;
private Utilisateur user;
private Utilisateur utilisateur;
private boolean remember = false;
private boolean admin;
#EJB //HUM Tu m'as vraiment dérangé.plus de 24h avant de me rappeller de te mettre.hum
private ProfilRoleServiceLocal prsbl;
public LoginBean() {
user = new Utilisateur();
utilisateur = new Utilisateur();
}
#PostConstruct
public void init() {
List<Role> all = rsbl.getAll();
if (all.isEmpty()) {
this.rsbl.saveOne(new Role(1, "Créer une Doléance", "doleance"));
this.rsbl.saveOne(new Role(2, "Modifier Doléance", "doleance"));
this.rsbl.saveOne(new Role(3, "Créer une fiche", "fiche"));
this.rsbl.saveOne(new Role(4, "Modifier une fiche", "fiche"));
this.rsbl.saveOne(new Role(5, "Créer une fiche d'exécution", "fiche d'exécution"));
this.rsbl.saveOne(new Role(6, "Modifier fiche d'exécution", "fiche d'exécution"));
this.rsbl.saveOne(new Role(7, "Créer une rapport de test", "rapport de test"));
this.rsbl.saveOne(new Role(8, "Modifier une rapport de test", "rapport de test"));
this.rsbl.saveOne(new Role(9, "Créer un produit", "produit"));
this.rsbl.saveOne(new Role(10, "Modifier un produit", "produit"));
this.rsbl.saveOne(new Role(11, "Créer un client", "client"));
this.rsbl.saveOne(new Role(12, "Modifier un client", "client"));
this.rsbl.saveOne(new Role(13, "Créer une direction", "direction"));
this.rsbl.saveOne(new Role(14, "Modifier une direction", "direction"));
this.rsbl.saveOne(new Role(15, "Créer une version", "version"));
this.rsbl.saveOne(new Role(16, "Modifier une version", "version"));
this.rsbl.saveOne(new Role(17, "Créer une mise à jour", "mise à jour"));
this.rsbl.saveOne(new Role(18, "Modifier une mise à jour", "mise à jour"));
this.rsbl.saveOne(new Role(19, "Créer une solution technique", "solution technique"));
this.rsbl.saveOne(new Role(20, "Modifier une solution technique", "solution technique"));
this.rsbl.saveOne(new Role(21, "Modifier planning", "planning"));
this.rsbl.saveOne(new Role(22, "Créer profil", "profil"));
this.rsbl.saveOne(new Role(23, "Modifier profil", "profil"));
this.rsbl.saveOne(new Role(24, "Créer securite", "securite"));
this.rsbl.saveOne(new Role(25, "Associer profil", "role"));
this.rsbl.saveOne(new Role(26, "Associer role", "role"));
this.rsbl.saveOne(new Role(27, "Activer compte", "compte"));
this.rsbl.saveOne(new Role(28, "Désactiver compte", "compte"));
this.rsbl.saveOne(new Role(29, "Modifier securite", "securite"));
}
List<Profil> alle = psbl.getAll();
if (alle.isEmpty()) {
this.psbl.saveOne(new Profil(1, "Administrateur", "administrer"));
this.psbl.saveOne(new Profil(2, "Super Admin", "Super admin"));
this.psbl.saveOne(new Profil(3, "Directeur", "directeur"));
this.psbl.saveOne(new Profil(4, "Responsable", "Responsable"));
this.psbl.saveOne(new Profil(5, "Collaborateur", "collaborer"));
this.psbl.saveOne(new Profil(6, "Technicien", "technicien"));
}
List<Profil> profils = psbl.getBy("nom", "Rohastrick");
UserTransaction tx = TransactionManager.getUserTransaction();
if (profils.isEmpty()) {
try {
tx.begin();
this.psbl.saveOne(new Profil(1, "Rohastrick", "rot2rick"));
List<Role> roles = this.rsbl.getAll();
for (Role role : roles) {
ProfilRole pr = new ProfilRole();
pr.setRole(role);
pr.setProfil(psbl.getOneBy("nom", "Rohastrick"));
prsbl.saveOne(pr);
}
Utilisateur ut = new Utilisateur();
ut.setNom("Rot2rick");
ut.setLogin("Rohastrick");
ut.setPass(new Sha256Hash("helen#").toHex());
ut.setEmail("admin");
ut.setTelephone("admin");
ut.setProfil(psbl.getOneBy("nom", "Rohastrick"));
ut.setActif(true);
usbl.saveOne(ut);
tx.commit();
} catch (Exception e) {
try {
tx.rollback();
} catch (IllegalStateException ex) {
Logger.getLogger(FicheBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(FicheBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SystemException ex) {
Logger.getLogger(FicheBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (AuthenticationException ex) {
ex.printStackTrace();
}
}
}
}
public boolean checkIntConnection() {
boolean status = false;
Socket sock = new Socket();
InetSocketAddress address = new InetSocketAddress("www.google.com", 80);
try {
sock.connect(address, 3000);
if (sock.isConnected()) {
status = true;
}
} catch (Exception e) {
} finally {
try {
sock.close();
} catch (Exception e) {
}
}
return status;
}
public void login() throws IOException {
System.out.println("Test Roler");
try {
System.out.println("user=" + username);
System.out.println("ps=" + password);
user = usbl.getOneBy("login", username);
if (user != null) {
if (user.isActif() == false) {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('error').show();");
username = "";
return;
}
}
if (user != null) {
boolean test = new Sha256Hash("admin").toHex().equals(user.getPass());
if (test && user.isActif() == false) {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogpasse').show();");
return;
}
}
UsernamePasswordToken token = new UsernamePasswordToken(username.trim(), password.trim());
token.setRememberMe(false);
try {
SecurityUtils.getSubject().login(token);
} catch (Exception e) {
System.out.println(""+ e.getMessage());
}
Subject subject = EntityRealm.getSubject();
if (!username.equalsIgnoreCase("admin")) {
if (subject.hasRole("Créer une fiche") || subject.hasRole("Modifier une fiche")
|| subject.hasRole("Créer une fiche d'exécution") || subject.hasRole("Modifier une fiche d'exécution")
|| subject.hasRole("Créer une Doléance") || subject.hasRole("Modifier une Doléance")
|| subject.hasRole("Créer un rapport de test") || subject.hasRole("Modifier un rapport de test")
|| subject.hasRole("Créer un produit") || subject.hasRole("Modifier un produit")
|| subject.hasRole("Créer une version à un produit") || subject.hasRole("Modifier une version du produit")
|| subject.hasRole("Créer une mise à jour") || subject.hasRole("Modifier une mise à jour")
|| subject.hasRole("Créer un Client") || subject.hasRole("Modifier Client")
|| subject.hasRole("Créer un Technicien") || subject.hasRole("Modifier un Technicien")
|| subject.hasRole("Créer une Solution Technique") || subject.hasRole("Modifier une Solution Technique")
|| subject.hasRole("Créer une Direction") || subject.hasRole("Modifier une Direction")) {
this.administration = "true";
} else {
this.administration = "false";
}
//connexion();
if (subject.hasRole("Créer une fiche")
|| subject.hasRole("Modifier fiche") || subject.hasRole("Modifier fiche")
|| subject.hasRole("Supprimer fiche")) {
this.fiche = "true";
} else {
this.fiche = "false";
}
if (subject.hasRole("Créer securite") || subject.hasRole("Modifier securite")
|| subject.hasRole("Créer profil") || subject.hasRole("Modifier profil")
|| subject.hasRole("Creer securite") || subject.hasRole("Associer profil")
|| subject.hasRole("Associer role") || subject.hasRole("Activer compte")
|| subject.hasRole("Désactiver compte")) {
this.securite = "true";
} else {
this.securite = "false";
}
if (subject.hasRole("Créer une Doléance")) {
this.creerDoleance = "true";
} else {
this.creerDoleance = "false";
}
if (subject.hasRole("Modifier une Doléance")) {
this.modifierDoleance = "true";
this.doleance = "true";
} else {
this.modifierDoleance = "false";
this.doleance = "false";
}
if (subject.hasRole("Créer un rapport de test") || subject.hasRole("Modifier un rapport de test")) {
this.RapportTest = "true";
} else {
this.RapportTest = "false";
}
if (subject.hasRole("Créer une fiche d'exécution") || subject.hasRole("Modifier une fiche d'exécution")) {
this.ficheExec = "true";
} else {
this.ficheExec = "false";
}
if (subject.hasRole("Créer une fiche d'exécution")) {
this.creerficheExec = "true";
} else {
this.creerficheExec = "false";
}
if (subject.hasRole("Modifier une fiche d'exécution")) {
this.modifierficheExec = "true";
} else {
this.modifierficheExec = "false";
}
if (subject.hasRole("Créer un rapport de test") || subject.hasRole("Modifier un rapport de test")) {
this.RapportTest = "true";
} else {
this.RapportTest = "false";
}
if (subject.hasRole("Créer un rapport de test")) {
this.creerRapportTest = "true";
} else {
this.creerRapportTest = "false";
}
if (subject.hasRole("Modifier un rapport de test")) {
this.modifierRapportTest = "true";
} else {
this.modifierRapportTest = "false";
}
if (subject.hasRole("Créer un produit") || subject.hasRole("Modifier un produit")) {
this.produit = "true";
} else {
this.produit = "false";
}
if (subject.hasRole("Créer un produit")) {
this.creerProduit = "true";
} else {
this.creerProduit = "false";
}
if (subject.hasRole("Modifier un produit")) {
this.modifierProduit = "true";
} else {
this.modifierProduit = "false";
}
if (subject.hasRole("Créer un technicien") || subject.hasRole("Modifier un technicien")) {
this.technicien = "true";
} else {
this.technicien = "false";
}
if (subject.hasRole("Créer un technicien")) {
this.creerTechnicien = "true";
} else {
this.creerTechnicien = "false";
}
if (subject.hasRole("Modifier un technicien")) {
this.modifierTechnicien = "true";
} else {
this.modifierTechnicien = "false";
}
if (subject.hasRole("Créer un client") || subject.hasRole("Modifier un client")) {
this.client = "true";
} else {
this.client = "false";
}
if (subject.hasRole("Créer un client")) {
this.creerClient = "true";
} else {
this.creerClient = "false";
}
if (subject.hasRole("Modifier un client")) {
this.modifierClient = "true";
} else {
this.modifierClient = "false";
}
if (subject.hasRole("Créer un client") || subject.hasRole("Modifier un client")) {
this.client = "true";
} else {
this.client = "false";
}
if (subject.hasRole("Créer un client")) {
this.creerClient = "true";
} else {
this.creerClient = "false";
}
if (subject.hasRole("Modifier un client")) {
this.modifierClient = "true";
} else {
this.modifierClient = "false";
}
if (subject.hasRole("Créer une solution technique") || subject.hasRole("Modifier une solution technique")) {
this.technique = "true";
} else {
this.technique = "false";
}
if (subject.hasRole("Créer une solution technique")) {
this.creerTechnique = "true";
} else {
this.creerTechnique = "false";
}
if (subject.hasRole("Modifier une solution technique")) {
this.modifierTechnique = "true";
} else {
this.modifierTechnique = "false";
}
if (subject.hasRole("Créer une direction") || subject.hasRole("Modifier une direction")) {
this.direction = "true";
} else {
this.direction = "false";
}
if (subject.hasRole("Créer une direction")) {
this.creerDirection = "true";
} else {
this.creerDirection = "false";
}
if (subject.hasRole("Modifier une direction")) {
this.modifierDirection = "true";
} else {
this.modifierDirection = "false";
}
if (subject.hasRole("Créer un produit") || subject.hasRole("Modifier un produit")) {
this.produit = "true";
} else {
this.produit = "false";
}
if (subject.hasRole("Créer un produit")) {
this.creerProduit = "true";
} else {
this.creerProduit = "false";
}
if (subject.hasRole("Modifier un produit")) {
this.modifierProduit = "true";
} else {
this.modifierProduit = "false";
}
if (subject.hasRole("Créer une mise à jour") || subject.hasRole("Modifier une mise à jour")) {
this.MAJ = "true";
} else {
this.MAJ = "false";
}
if (subject.hasRole("Créer une mise à jour")) {
this.creerMAJ = "true";
} else {
this.creerMAJ = "false";
}
if (subject.hasRole("Modifier une mise à jour")) {
this.modifierMAJ = "true";
} else {
this.modifierMAJ = "false";
}
if (subject.hasRole("Créer un client") || subject.hasRole("Modifier un client")) {
this.client = "true";
} else {
this.client = "false";
}
if (subject.hasRole("Créer un client")) {
this.creerClient = "true";
} else {
this.creerClient = "false";
}
if (subject.hasRole("Modifier un client")) {
this.modifierClient = "true";
} else {
this.modifierClient = "false";
}
if (subject.hasRole("Créer un profil") || subject.hasRole("Modifier un profil")) {
this.profil = "true";
} else {
this.profil = "false";
}
if (subject.hasRole("Créer un profil")) {
this.creerProfil = "true";
} else {
this.creerProfil = "false";
}
if (subject.hasRole("Modifier un profil")) {
this.modifierProfil = "true";
} else {
this.modifierProfil = "false";
}
if (subject.hasRole("Associer un profil")) {
this.associerProfil = "true";
} else {
this.associerProfil = "false";
}
if (subject.hasRole("Associer role")) {
this.associerRole = "true";
} else {
this.associerRole = "false";
}
if (subject.hasRole("Activer un compte")) {
this.activerCompte = "true";
} else {
this.activerCompte = "false";
}
if (subject.hasRole("Désactiver un compte")) {
this.desactiverCompte = "true";
} else {
this.desactiverCompte = "false";
}
}
SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(Faces.getRequest());
Faces.redirect(savedRequest != null ? savedRequest.getRequestUrl() : "index.xhtml");
} catch (AuthenticationException e) {
e.printStackTrace();
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Nom d'utlisateur ou mot de passe incorrect", "");
FacesContext.getCurrentInstance().addMessage("", mf);
}
//return "index";
}
public String currentUser() {
Utilisateur user = EntityRealm.getUser();
if (user == null) {
return "Admin";
}
return EntityRealm.getUser().getLogin();
}
public Date sessionTime() {
return EntityRealm.getSubject().getSession().getStartTimestamp();
}
public void logout() {
try {
EntityRealm.getSubject().logout();
Faces.redirect("login.xhtml");
username = "";
} catch (IOException ex) {
}
}
public void mot() {
System.out.println("test");
}
public void modifierPasse() {
System.out.println("test");
System.out.println(newPass);
System.out.println(retapPass);
if (newPass.trim().equals(retapPass.trim())) {
user.setPass(new Sha256Hash(newPass.trim()).toHex());
user.setQuestion(question);
user.setReponse(reponse);
usbl.updateOne(user);
question = "";
reponse = "";
RequestContext.getCurrentInstance().execute("PF('dialogpasse').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Mot de passe corriger", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Les mots de passe ne concorde pas", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
}
public void modifierPasse2() {
if (new Sha256Hash(lastPass).toHex().equals(EntityRealm.getUser().getPass())) {
if (newPass.trim().equals(retapPass.trim())) {
if (new Sha256Hash(newPass).toHex().equals(EntityRealm.getUser().getPass())) {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Tapez un mot de passe différent de l'ancien", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
newPass = "";
lastPass = "";
retapPass = "";
} else {
EntityRealm.getUser().setPass(new Sha256Hash(newPass.trim()).toHex());
usbl.updateOne(EntityRealm.getUser());
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Mot de passe corrigé", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogpasse').hide()");
}
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Les mots de passe ne concorde pas", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
newPass = "";
lastPass = "";
retapPass = "";
}
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"mot de passe incorrect!!!", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
newPass = "";
lastPass = "";
retapPass = "";
}
}
public void reinitialiserPasse() {
Utilisateur u = this.usbl.getOneBy("login", per);
if (u.isActif() == true) {
if (reponse.equals(u.getReponse())) {
u.setPass(new Sha256Hash("admin").toHex());
u.setQuestion(null);
u.setReponse(null);
usbl.updateOne(u);
question = "";
reponse = "";
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogRecup').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Mot de passe réinitialisé", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
} else {
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"La reponse est fausse", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
}
}
public String recupererQuestion() {
if (!per.equals("")) {
Utilisateur u = this.usbl.getOneBy("login", per);
String quest = "";
if (u != null) {
if (!u.getPass().equals(new Sha256Hash("admin").toHex())) {
if (u.isActif() == true) {
quest = u.getQuestion();
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogRecup').show();");
context.execute("PF('dialogOublie').hide();");
return quest;
} else {
per = "";
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogOublie').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"Votre compte est inactif,contactez l'administrateur", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
} else {
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dialogOublie').hide();");
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Connectez vous à votre compte pour changer votre mot de passe", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
} else {
per = "";
FacesMessage mf = new FacesMessage(FacesMessage.SEVERITY_FATAL,
"le login saisi est inconnu", "");
FacesContext.getCurrentInstance().addMessage("erreur_login", mf);
}
}
return "";
}
this is the JSF page
<h:form id="login" >
<p:growl id="message" life="4000" showSummary="true" />
<p:outputPanel autoUpdate="true" style="background-image:">
<div class="card login-panel ui-fluid" style=" border-radius: 10px;">
<div class="ui-g">
<div class="ui-g-12">
<p:graphicImage name="images/logo2x.png" library="ultima-layout" />
</div>
<div class="ui-g-12">
<h:panelGroup styleClass="md-inputfield">
<p:inputText id="identifiant" value="#{loginBean.username}" />
<label>Email...</label>
</h:panelGroup>
</div>
<div class="ui-g-12">
<h:panelGroup styleClass="md-inputfield">
<p:password id="motdepasse" value="#{loginBean.password}" />
<label>Mot de Passe...</label>
</h:panelGroup>
</div>
<div class="ui-g-12">
<p:commandButton process="#form" value="Se connecter" icon="ui-icon-person" update="message" actionListener="#{loginBean.login()}" />
<p:commandButton value="Mot de passe oublié" icon="ui-icon-help" styleClass="secondary" onclick="PF('dialogOublie').show()"/>
</div>
</div>
</div>
</p:outputPanel>
</h:form>
and the error
Caused by: org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.

Slim framework rest api update from v2 to v3

hi i'm new to slim framework and it's basics and I have found many examples of rest apis based on v2 (http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/)I really like the code partition and methods of v2 but I could not update to v3
can anyone help me with this
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// ID utilisateur - variable globale
$user_id = NULL;
/**
* Ajout de Couche intermédiaire pour authentifier chaque demande
* Vérifier si la demande a clé API valide dans l'en-tête "Authorization"
*/
function authenticate(\Slim\Route $route) {
// Obtenir les en-têtes de requêtes
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
// Vérification de l'en-tête d'autorisation
if (isset($headers['Authorization'])) {
$db = new DbHandler();
// Obtenir la clé d'api
$api_key = $headers['Authorization'];
// Valider la clé API
if (!$db->isValidApiKey($api_key)) {
// Clé API n'est pas présente dans la table des utilisateurs
$response["error"] = true;
$response["message"] = "Accès Refusé. Clé API invalide";
echoRespnse(401, $response);
$app->stop();
} else {
global $user_id;
// Obtenir l'ID utilisateur (clé primaire)
$user_id = $db->getUserId($api_key);
}
} else {
// Clé API est absente dans la en-tête
$response["error"] = true;
$response["message"] = "Clé API est manquante";
echoRespnse(400, $response);
$app->stop();
}
}
/**
* ----------- MÉTHODES sans authentification---------------------------------
*/
/**
* Enregistrement de l'utilisateur
* url - /register
* methode - POST
* params - name, email, password
*/
$app->post('/register', function() use ($app) {
// vérifier les paramètres requises
verifyRequiredParams(array('name', 'email', 'password'));
$response = array();
// lecture des params de post
$name = $app->request->post('name');
$email = $app->request->post('email');
$password = $app->request->post('password');
// valider adresse email
validateEmail($email);
$db = new DbHandler();
$res = $db->createUser($name, $email, $password);
if ($res == USER_CREATED_SUCCESSFULLY) {
$response["error"] = false;
$response["message"] = "Vous êtes inscrit avec succès";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Oops! Une erreur est survenue lors de l'inscription";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Désolé, cet E-mail éxiste déja";
}
// echo de la repense JSON
echoRespnse(201, $response);
});
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Manipulation paramsde la demande PUT
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
//Champ (s) requis sont manquants ou vides
// echo erreur JSON et d'arrêter l'application
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Champ(s) requis ' . substr($error_fields, 0, -2) . ' est (sont) manquant(s) ou vide(s)';
echoRespnse(400, $response);
$app->stop();
}
}
/**
* Validation adresse e-mail
*/
function validateEmail($email) {
$app = \Slim\Slim::getInstance();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response["error"] = true;
$response["message"] = "Adresse e-mail n'est pas valide";
echoRespnse(400, $response);
$app->stop();
}
}
/**
* Faisant écho à la réponse JSON au client
* #param String $status_code Code de réponse HTTP
* #param Int $response response Json
*/
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Code de réponse HTTP
$app->status($status_code);
// la mise en réponse type de contenu en JSON
$app->contentType('application/json');
echo utf8_encode(json_encode($response));
}
$app->run();
well after deep search i changed the code to be like this
require '../libs/vendor/autoload.php';
$app = new Slim\App( [
'settings' => [
'addContentLengthHeader' => false
]
]);
$verifyRequiredParams = function ($request, $response, $next) {
$route = $request->getAttribute('route');
$validators = $route->getArgument('validators');
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Manipulation paramsde la demande PUT
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
parse_str($request->getBody(), $request_params);
}
foreach ($validators as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
//Champ (s) requis sont manquants ou vides
// echo erreur JSON et d'arrêter l'application
$resp=array();
$resp['error']=true;
$resp["message"] = 'Champ(s) requis ' . substr($error_fields, 0, -2) . ' est (sont) manquant(s) ou vide(s)';
$response= $response->withJson($resp, 400);
}else{ $response = $next($request, $response);}
return $response;
};
$authenticate=function($request, $response, $next) {
// Obtenir les en-têtes de requêtes
$headers = apache_request_headers();
$resp = array();
// Vérification de l'en-tête d'autorisation
if (isset($headers['Authorization'])) {
$db = new DbHandler();
// Obtenir la clé d'api
$api_key = $headers['Authorization'];
// Valider la clé API
if (!$db->isValidApiKey($api_key)) {
// Clé API n'est pas présente dans la table des utilisateurs
$resp["error"] = true;
$resp["message"] = "Accès Refusé. Clé API invalide";
$response=$response->withJson($resp, 401);
} else {
global $user_id;
// Obtenir l'ID utilisateur (clé primaire)
$user_id = $db->getUserId($api_key);
$response=$response = $next($request, $response);
}
} else {
// Clé API est absente dans la en-tête
$resp["error"] = true;
$resp["message"] = "Clé API est manquante";
$response=$response->withJson($resp, 400);
}
return$response;
};
$app->post('/task', function ($request, $response, $args) {
$resp = array();
$task = $request->getParsedBody()['task'];
global $user_id;
$db = new DbHandler();
//Création d'une nouvelle tâche
$task_id = $db->createTask($user_id, $task);
if ($task_id != NULL) {
$resp["error"] = false;
$resp["message"] = "Tâche créé avec succès";
$resp["task_id"] = $task_id;
$response=$response->withJson($resp, 201);
} else {
$resp["error"] = true;
$resp["message"] = "Impossible de créer la tâche. S'il vous plaît essayer à nouveau";
$response=$response->withJson($resp, 200);
}
return $response;
})->setArguments(['validators' => ['task']])->add($verifyRequiredParams)->add($authenticate);
$app->run();

Add/update roster as an admin using php

As per my project's nature, I want to add/update roster information using some script(php). I want to do it in the same way, it is done by web admin interface of ejabberd manually. But i want to automate this. Is there any way to do this?
Any suggestion on how to achieve this goal is highly appreciated. Thanks in advance !
If you are using Openfire, you can just use the Userservice plugin, which will allow you to administer user rosters via HTTP requests
<?php
/**
* Created by JetBrains PhpStorm.
* User: Abel Espinosa Cañive
* Date: 8/5/15
* Time: 7:43 PM
* To change this template use File | Settings | File Templates.
*/
/*
ERROR CODE:
0 :Success
Other Number:Error
*/
define ( "MAX_SIZE", "5120" ); // 5MB MAX file size
define ( "DOMAIN", "my.domain.com" );
class eJabberedPlugin
{
var $display_debug_info;
//activa la opcion de debugueo del XMPP
function eJabberedPlugin($v_display_debug_info=false)
{
$this->display_debug_info = $v_display_debug_info;
}
//Crea un nuevo usuario
//$UserLogin : usuario que se creará
//$UserPass : contraseña para el usuario nuevo
function createNewUserREST($UserLogin,$UserPass)
{
$url = "http://DOMAIN:5280/rest/";
$request = "register $UserLogin DOMAIN $UserPass";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Adiciona Amigo1 a Amigo2 y viceversa (forzado)
//$user1 : usuario que desea agregar a $user2
//$user2 : usuario que desea agregar a $user1
//$nick_user1 : nick que le dará el $user2 al $user1 en su roster
//$nick_user2 : nick que le dará el $user1 al $user2 en su roster
//$group1 : Grupo en el roster de $user1 que se agregará al $user2
//$group2 : Grupo en el roster de $user2 que se agregará al $user1
function addFriendREST($user1,$user2,$nick_user1="",$nick_user2="",$group1="Friends",$group2="Friends")
{
$url = "http://DOMAIN:5280/rest/";
$exist_user1 = $this->checkUser($user1);
$exist_user2 = $this->checkUser($user2);
if($exist_user1==0 && $exist_user2==0)
{
$request1 = "add_rosteritem $user1 DOMAIN $user2 DOMAIN $nick_user2 $group1 both";
$request2 = "add_rosteritem $user2 DOMAIN $user1 DOMAIN $nick_user1 $group2 both";
$response1 = $this->sendRESTRequest($url, $request1);
$response2 = $this->sendRESTRequest($url, $request2);
}
else
{
$response1 = $exist_user1;
$response2 = $exist_user2;
}
$response_array = [$response1,$response2];
return $response_array;
}
//Elimina un usuario del servidor
//$username : Usuario que se eliminará
function deleteUserREST($username)
{
$url = "http://DOMAIN:5280/rest/";
$request = "unregister $username DOMAIN";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Agrega o cambia un avatar a un usuario dado
//$username : usuario que se modificará
//$photo_url : archivo de la imagen nueva
function addAvatarREST($username,$photo_url)
{
$url = "http://DOMAIN:5280/rest/";
$raw_file = file_get_contents($photo_url["tmp_name"]);
$photo = base64_encode($raw_file);
$request = "set_vcard2 $username DOMAIN PHOTO BINVAL $photo";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Verifica si el usuario existe en el servidor
//$username : Usuario a verificar
function checkUser($username)
{
$url = "http://DOMAIN:5280/rest/";
$request = "check_account $username DOMAIN";
$response = $this->sendRESTRequest($url, $request);
return $response;
}
//Obtiene una lista de todos los usuarios registrados en el servidor
function allUsers()
{
$url = "http://DOMAIN:5280/rest/";
$request = "registered_users DOMAIN";
$response = $this->sendRESTRequest($url, $request);
$arr = str_split($response);
$collecting = "";
$result = [];
for ($i = 0; $i < count($arr); $i++) {
if (ctype_alnum($arr[$i])==true) {
$collecting.=$arr[$i];
if ($i==count($arr)-1) {
array_push($result,$collecting);
}
}
else
{
array_push($result,$collecting);
$collecting = "";
}
}
return $result;
}
//Ejecuta las consultas con el servidor
//$url : Direccion del servidor REST
//$xml : Consulta
function sendRESTRequest ($url, $xml) {
$context = stream_context_create(
array('http' =>
array(
'method' => "POST",
'header' => "Content-Length: ".strlen($xml),
'content' => $xml
)
)
);
$file = file_get_contents($url, false, $context);
return "$file";
}
//Obtiene la extension del archivo adjunto
//$str : Nombre del archivo que se verifica
function getExtension($str) {
$i = strrpos ( $str, "." );
if (! $i) {
return "";
}
$l = strlen ( $str ) - $i;
$ext = substr ( $str, $i + 1, $l );
return $ext;
}
}
//*****FIN DE LA CLASE*****//
// Crea una instancia de la clase eJabberedPlugin
$obj = new eJabberedPlugin();
// Ahora comenzamos a usar la clase de arriba :)
//Crear nuevo usuario
if(isset($_POST['action']) && $_POST['action']=='newUser')
{
if(isset($_POST['user']) && isset($_POST['pass']))
{
$result = $obj->createNewUserREST($_POST['user'],$_POST['pass']);
if($result==0)
{
echo "created ok";
}
else
{
echo "not created, error:$result";
}
}
}
//Eliminar usuario
elseif(isset($_POST['action']) && $_POST['action']=='delUser')
{
if(isset($_POST['user']))
{
$result = $obj->deleteUserREST($_POST['user']);
if($result==0)
{
echo "deleted ok";
}
else
{
echo "not deleted, error:$result";
}
}
}
//Agregar amigos
elseif(isset($_POST['action']) && $_POST['action']=='addFriend')
{
if(isset($_POST['userFriend1']) && isset($_POST['userFriend2']) && isset($_POST['nickUser1']) && isset($_POST['nickUser2']) && isset($_POST['groupUser1']) && isset($_POST['groupUser2']) )
{
$result = $obj->addFriendREST($_POST['userFriend1'],$_POST['userFriend2'],$_POST['nickUser1'],$_POST['nickUser2'],$_POST['groupUser1'],$_POST['groupUser2']);
if(count($result)==2 && $result[0]==0 && $result[1]==0)
{
echo "added ok";
}
else
{
echo "not added, error:<br>";
if($result[0]==1 && $result[1]==0)
{
echo "Usuario ".$_POST['userFriend1'].": Usuario no registrado.<br>";
echo "Usuario ".$_POST['userFriend2'].": ".$result[1]." errores<br>";
}
elseif($result[0]==0 && $result[1]==1)
{
echo "Usuario ".$_POST['userFriend1'].": ".$result[0]." errores<br>";
echo "Usuario ".$_POST['userFriend2'].": Usuario no registrado.<br>";
}
else
{
echo "Usuarios ".$_POST['userFriend1']." y ".$_POST['userFriend2']." no registrados.<br>";
}
}
}
}
//Agregar avatar
elseif(isset($_POST['action']) && $_POST['action']=='addAvatar')
{
if(isset($_POST['user']) && isset($_FILES['avatar']))
{
$filename = stripslashes ( $_FILES ["avatar"] ["name"] );
$size = filesize ( $_FILES ["avatar"] ["tmp_name"]);
// Convert extension into a lower case format
$ext = $obj->getExtension ( $filename );
$ext = strtolower ( $ext );
// File extension check
// Valid image formats
$valid_formats = array ("jpg","png","gif","bmp","jpeg");
if (in_array ( $ext, $valid_formats )) {
// File size check
if ($size < (MAX_SIZE * 1024)) {
$result = $obj->addAvatarREST($_POST['user'],$_FILES['avatar']);
if($result==0)
{
echo "added ok";
}
else
{
echo "not added, error:$result";
}
}
}
}
}
?>