Example usage for org.apache.shiro SecurityUtils getSubject

List of usage examples for org.apache.shiro SecurityUtils getSubject

Introduction

In this page you can find the example usage for org.apache.shiro SecurityUtils getSubject.

Prototype

public static Subject getSubject() 

Source Link

Document

Returns the currently accessible Subject available to the calling code depending on runtime environment.

Usage

From source file:au.org.theark.web.pages.login.LoginForm.java

License:Open Source License

/**
 * Authenticate the given user//from w  ww .j ava 2  s .c o  m
 * @param user
 *           the given user to authenticate
 * @return
 */
public final boolean authenticate(ArkUserVO user) {
    Subject subject = SecurityUtils.getSubject();
    // Disable Remember me
    UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(),
            user.getPassword(), false);

    try {
        // This will propagate to the Realm
        subject.login(usernamePasswordToken);
        return true;
    } catch (IncorrectCredentialsException e) {
        String errMessage = getLocalizer().getString("page.incorrect.password", LoginForm.this,
                "Password is incorrect.");
        getSession().error(errMessage);
        log.error(e.getMessage());
    } catch (UnknownAccountException e) {
        String errMessage = getLocalizer().getString("page.account.notfound", LoginForm.this,
                "User account not found.");
        getSession().error(errMessage);
        log.error(e.getMessage());
    } catch (AuthenticationException e) {
        String errMessage = getLocalizer().getString("page.invalid.username.password", LoginForm.this,
                "Invalid username and/or password.");
        getSession().error(errMessage);
        log.error(e.getMessage());
    } catch (Exception e) {
        String errMessage = getLocalizer().getString("page.login.failed", LoginForm.this, "Login Failed.");
        getSession().error(errMessage);
        log.error(e.getMessage());
    }
    return false;
}

From source file:au.org.theark.web.pages.login.LogoutPage.java

License:Open Source License

@SuppressWarnings("unchecked")
public LogoutPage(final PageParameters parameters) {

    System.out.println("\n Constructor LogoutPage(final PageParameters param)");

    String page = parameters.get(REDIRECT_PAGE).toString();

    Class<? extends Page> pageClass;

    if (page != null) {
        try {//  w  w w  .jav  a 2  s .  com
            pageClass = (Class<? extends Page>) Class.forName(page);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    } else {
        System.out.println("Send the user to LoginPage");
        pageClass = LoginPage.class; // getApplication().getHomePage();
    }

    this.setStatelessHint(true);
    setResponsePage(pageClass);

    // this should remove the cookie...
    Subject subject = SecurityUtils.getSubject();
    // Place the selected study in session context for the user
    SecurityUtils.getSubject().getSession().removeAttribute(au.org.theark.core.Constants.STUDY_CONTEXT_ID);
    SecurityUtils.getSubject().getSession().removeAttribute(au.org.theark.core.Constants.PERSON_CONTEXT_ID);
    SecurityUtils.getSubject().getSession().removeAttribute(au.org.theark.core.Constants.PERSON_TYPE);
    subject.logout();
    Session.get().invalidateNow(); // invalidate the wicket session
    return;
}

From source file:au.org.theark.web.pages.login.LogoutPage.java

License:Open Source License

private void doLogoutAndAddRedirect(final CharSequence url, final int waitBeforeRedirectInSeconds) {
    System.out.println("\n doLogoutAndAddRedirect() invoked");

    this.setStatelessHint(true);

    // this should remove the cookie...
    Subject subject = SecurityUtils.getSubject();
    subject.logout();/* ww w  .j av a2s. c  o  m*/

    final WebMarkupContainer redirect = new WebMarkupContainer("redirect");
    final String content = waitBeforeRedirectInSeconds + ";URL=" + url;
    redirect.add(new AttributeModifier("content", new Model<String>(content)));
    add(redirect);

    // invalidate the session
    Session.get().invalidateNow(); // invalidate the wicket session

    // HYMMMM
    Cookie c = new Cookie("rememberMe", "xxx");
    c.setMaxAge(0);
    ((WebResponse) RequestCycle.get().getResponse()).addCookie(c);
}

From source file:b4f.seguridad.filtros.RequieresFilter.java

@Override
public void filter(ContainerRequestContext crc) throws IOException {
    Requieres requieres = resourceInfo.getResourceMethod().getAnnotation(Requieres.class);
    //        System.out.println("Authorization filter: " + Arrays.toString(requieres.roles()));

    //        crc.getHeaderString("Authorization");
    Subject sub = SecurityUtils.getSubject();
    Object principal = sub.getPrincipal();
    if (!(principal instanceof Usuario)) {
        crc.abortWith(Response.status(401).build());
        return;// w  ww  .  j a v a 2  s  .  c  om
    }

    Usuario user = (Usuario) principal;
    //        System.out.println("Rol->" + user.getRol());

    boolean pass = false;
    for (String r : requieres.roles()) {
        if (r.equalsIgnoreCase(user.getRol().getDescripcion())) {
            pass = true;
            break;
        }
    }
    if (!pass) {
        crc.abortWith(Response.status(403).build());
    }

}

From source file:b4f.servicios.AuthService.java

@Path("/logout")
@GET/*w w  w .  ja  v  a  2  s.c  o m*/
public Response logout() {
    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser != null && currentUser.isAuthenticated()) {
        currentUser.logout();
        return Response.ok().build();
    }
    return Response.status(Response.Status.BAD_REQUEST).entity("Not logged in").type(MediaType.TEXT_PLAIN)
            .build();
}

From source file:b4f.servicios.PuntoService.java

@PUT
@Path("{id}/reservas/{idReserva}")
@Requieres(roles = { "FUNCIONARIO" })
public Response registrarPrestamo(@PathParam("id") long id_punto, @PathParam("idReserva") long id_reserva,
        JSONObject data) {/* ww  w.j a va2  s.  c  o m*/

    try {
        entityManager.getTransaction().begin();
        Punto punto = entityManager.find(Punto.class, id_punto);
        if (punto == null) {
            throw new Exception("el punto con id='" + id_punto + "' no existe");
        }
        Reserva reserva = entityManager.find(Reserva.class, id_reserva);
        if (reserva == null) {
            throw new Exception("La reserva con id " + id_reserva + " no existe");
        }

        final Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        if (!(principal instanceof Usuario)) {
            throw new Exception("Usuario no autenticado");
        }
        Usuario user = (Usuario) principal;

        if (!data.containsKey("accion")) {
            throw new Exception("Accion no especificada (PRESTAMO,RETORNO)");
        }

        String accion = data.get("accion").toString();

        if (!accion.equalsIgnoreCase("PRESTAMO") && !accion.equalsIgnoreCase("RETORNO")) {
            throw new Exception("Accion invalida (PRESTAMO, RETORNO)");
        }

        if (accion.equalsIgnoreCase("PRESTAMO")) {
            //HACER EFECTIVA LA RESERVA

            if (reserva.getPuntoPrestamo().getId() != id_punto) {
                throw new Exception("El punto de prestamo no coincide con el de la reserva");
            }

            if (reserva.getEstado() != Reserva.Estado.RESERVADA) {
                throw new Exception("La bicicleta no puede ser entregada.");
            }

            reserva.setPuntoPrestamo(punto);
            reserva.setEstado(Reserva.Estado.EN_PRESTAMO);
            reserva.getBici().setEstado(Bici.Estado.PRESTADA);
            reserva.getBici().setPunto(null);

            reserva.setFuncionarioEntrega(user);
        } else {
            // HACER EFECTIVA LA ENTREGA 
            if (reserva.getEstado() != Reserva.Estado.EN_PRESTAMO)
                throw new Exception("La reserva no se encuentra en prestamo");
            reserva.setEstado(Reserva.Estado.FINALIZADA);
            reserva.setPuntoRetorno(punto);
            reserva.getBici().setEstado(Bici.Estado.DISPONIBLE);
            reserva.getBici().setPunto(punto);
            punto.addBici(reserva.getBici());

            reserva.setFuncionarioRecibo(user);
            reserva.setFecha_retorno(System.currentTimeMillis());

            JSONArray arr = (JSONArray) data.get("multas");
            Query q = entityManager.createQuery("Select m FROM Multa m WHERE m.id=:id");
            if (arr != null) {
                for (int i = 0; i < arr.size(); i++) {
                    long id_multa = Long.parseLong(arr.get(i).toString());
                    q.setParameter("id", id_multa);
                    List res = q.getResultList();
                    if (res.isEmpty()) {
                        throw new Exception("La multa con id " + id_multa + " no existe");
                    }
                    Multa multa = (Multa) res.get(0);
                    reserva.getMultas().add(multa);

                }
            }

        }

        entityManager.getTransaction().commit();

        return Response.status(200).entity(reserva).build();

    } catch (Exception e) {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
        }
        JSONObject err = new JSONObject();
        err.put("error", e.getMessage());
        return Response.status(400).entity(err).build();
    } finally {
        entityManager.clear();
        entityManager.close();
    }

}

From source file:b4f.servicios.ReservaService.java

/**
 * data:/*  ww  w.ja  v a  2 s. co  m*/
 *  - cedula
 *  - id_punto
 *  - id_tipo_bici (id)
 *  - fecha (milisegundos)
 * @param data
 * @return 
 */
//    @POST
//    public Response POST(JSONObject data) {
//
//        JSONObject rta = new JSONObject();
//
//        try {
//            entityManager.getTransaction().begin();
//            
//            if(!data.containsKey("cedula") || !data.containsKey("id_punto") || !data.containsKey("id_tipo_bici") || !data.containsKey("fecha"))
//                throw new Exception("Peticion invalida");
//            
//            String cedula = data.get("cedula").toString();
//            long id_punto = Long.parseLong( data.get("id_punto").toString());
//            long id_tipo_bici = Long.parseLong(data.get("id_tipo_bici").toString());
//            long fecha = Long.parseLong(data.get("fecha").toString());
//          
//            
//            Reserva reserva = Reserva.crearReserva(entityManager, cedula, id_punto, id_tipo_bici, fecha);
//            
//            entityManager.persist(reserva);
//            entityManager.getTransaction().commit();
//            entityManager.refresh(reserva);
//            rta.put("reserva", reserva);
//            
//        }  catch (Exception | Error t) {
//            System.err.println("[ERROR] " + t.getMessage());
//            rta.put("error", t.getMessage());
//            if (entityManager.getTransaction().isActive()) {
//                entityManager.getTransaction().rollback();
//            }
//            return Response.status(400).entity(rta).build();
//        } finally {
//            entityManager.clear();
//            entityManager.close();
//        }
//
//        return Response.status(201).entity(rta).build();
//    }

// me mandan el id del punto de entrega y retorno y obengo el de usuario
@POST
@Path("{id}/calificaciones")
public Response calificarReserva(@PathParam("id") long id, JSONObject data) {
    JSONObject rta = new JSONObject();

    try {
        entityManager.getTransaction().begin();

        Reserva r = entityManager.find(Reserva.class, id);

        final Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        if (!(principal instanceof Usuario)) {
            throw new Exception("Usuario no autenticado");
        }
        Usuario user = (Usuario) principal;

        long id_punto = r.getPuntoPrestamo().getId();
        long id_punto_retorno = r.getPuntoRetorno().getId();
        Double calificacionEntrega = Double.parseDouble(data.get("calificacion_entega").toString());
        Double calificacionRetorno = Double.parseDouble(data.get("retorno").toString());

        Calificacion c = Calificacion.crearCalificacion(entityManager, user.getId(), id_punto, id_punto_retorno,
                calificacionEntrega, calificacionRetorno);

        entityManager.persist(c);
        entityManager.getTransaction().commit();
        entityManager.refresh(c);
        rta.put("calificacion", c);

    } catch (Exception | Error t) {
        System.err.println("[ERROR] " + t.getMessage());
        rta.put("error", t.getMessage());
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
        }
        return Response.status(400).entity(rta).build();
    } finally {
        entityManager.clear();
        entityManager.close();
    }

    return Response.status(201).entity(rta).build();
}

From source file:beans.ShiroLoginBean.java

/**
 * Try and authenticate the user/*w w w . j a  va 2  s.  c om*/
 */
public void doLogin() {
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);

        if (subject.hasRole("admin")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("admin/index.xhtml");
        } else {
            FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
        }
    } catch (UnknownAccountException ex) {
        facesError("Unknown account");
        //log.error(ex.getMessage(), ex);
    } catch (IncorrectCredentialsException ex) {
        facesError("Wrong password");
        //log.error(ex.getMessage(), ex);
    } catch (LockedAccountException ex) {
        facesError("Locked account");
        //log.error(ex.getMessage(), ex);
    } catch (AuthenticationException | IOException ex) {
        facesError("Unknown error: " + ex.getMessage());
        //log.error(ex.getMessage(), ex);
    } finally {
        token.clear();
    }
}

From source file:beans.ShiroLoginBean.java

public void doLogout() throws IOException {
    SecurityUtils.getSubject().logout();
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    FacesContext.getCurrentInstance().getExternalContext().redirect("login.xhtml");
}

From source file:blade.authenticator.shiro.ShiroAuthenticatorPre.java

License:Apache License

@Override
public int authenticateByEmailAddress(long companyId, String emailAddress, String password,
        Map<String, String[]> headerMap, Map<String, String[]> parameterMap) throws AuthException {

    _log.info("authenticateByEmailAddress");

    UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(emailAddress, password);

    Subject currentUser = SecurityUtils.getSubject();

    try {/*from   w  ww. java2s. co  m*/
        currentUser.login(usernamePasswordToken);

        boolean authenticated = currentUser.isAuthenticated();

        if (authenticated) {
            _log.info("authenticated");
            return SKIP_LIFERAY_CHECK;
        } else {
            return FAILURE;
        }
    } catch (AuthenticationException e) {
        _log.error(e.getMessage(), e);
        throw new AuthException(e.getMessage(), e);
    }
}