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:br.uff.ic.security.ShiroLoginBean.java

/**
 * Try and authenticate the user/*  w w  w  . ja v a  2  s. co  m*/
 */
public void doLogin() {
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword(), getRememberMe());

    try {
        subject.login(token);
        SessionUtil.setParam("usuario", usuarioFacade.autentificar(getUsername(), getPassword()));
        if (subject.hasRole("ADMINISTRADOR")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("admin/index.xhtml");
        } else if (subject.hasRole("GERENTE")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("gerente/index.xhtml");
        } else if (subject.hasRole("ASSISTENTE")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("assistente/index.xhtml");
        } else if (subject.hasRole("PROFESSOR")) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("professor/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);
    } catch (Exception ex) {
        facesError("Unknown error: " + ex.getMessage());
        log.error(ex.getMessage(), ex);
    } finally {
        token.clear();
    }
}

From source file:ch.bastiangardel.easypay.rest.CheckOutController.java

License:Open Source License

@RequestMapping(value = "/checkoutlist", method = GET)
@RequiresAuthentication/*from w w  w  .  java  2 s  .com*/
@RequiresRoles("SELLER")
public List<CheckOutSummaryDTO> getUserCheckOuts() {
    log.info("get User Checkouts {}");
    final Subject subject = SecurityUtils.getSubject();
    String email = (String) subject.getSession().getAttribute("email");

    User user = userRepo.findByEmail(email);

    List<CheckOutSummaryDTO> list = new LinkedList<>();
    for (CheckOut checkOut : user.getCheckoutInPossesion()) {
        CheckOutSummaryDTO checkOutSummaryDTO = new CheckOutSummaryDTO();
        checkOutSummaryDTO.modelToDto(checkOut);
        list.add(checkOutSummaryDTO);

    }

    return list;
}

From source file:ch.bastiangardel.easypay.rest.CheckOutController.java

License:Open Source License

@RequestMapping(value = "/receipttopay", method = DELETE)
@RequiresAuthentication//from w  w w  . j  ava2s . co m
@RequiresRoles("SELLER")
public void deleteLastreceipt(@RequestParam("uuid") String uuid) {
    CheckOut checkOut;

    checkOut = checkoutRepo.findByUuid(uuid);

    if (checkOut == null)
        throw new CheckOutNotFoundException("Not Found CheckOut with UUID : " + uuid);

    final Subject subject = SecurityUtils.getSubject();

    if (!checkOut.getOwner().getEmail().equals(subject.getSession().getAttribute("email")))
        throw new OwnerException("Your are not the owner of this checkout");

    Receipt receipt = checkOut.getLastReceipt();

    if (receipt == null)
        throw new NoReceiptToPayExeption("No Receipt to Delete");

    checkOut.setLastReceipt(null);

    checkoutRepo.save(checkOut);

    receiptRepo.delete(receipt);
}

From source file:ch.bastiangardel.easypay.rest.ReceiptController.java

License:Open Source License

@RequestMapping(method = POST)
@RequiresAuthentication// w  ww .  j  a va2s .c o m
@RequiresRoles("SELLER")
public SuccessMessageDTO create(@RequestBody ReceiptCreationDTO receiptCreationDTO) {
    log.info("create new Receipt {}");

    CheckOut checkOut;

    checkOut = checkOutRepo.findByUuid(receiptCreationDTO.getUuidCheckout());

    if (checkOut == null)
        throw new CheckOutNotFoundException(
                "Not Found CheckOut with UUID : " + receiptCreationDTO.getUuidCheckout());

    final Subject subject = SecurityUtils.getSubject();

    log.info("{} create new Receipt from {}", checkOut.getOwner().getEmail(),
            subject.getSession().getAttribute("email"));

    if (!checkOut.getOwner().getEmail().equals(subject.getSession().getAttribute("email")))
        throw new OwnerException("Your are not the owner of this checkout");

    if (checkOut.getLastReceipt() != null)
        throw new ReceiptToPayAlreadyExist("There is already a receipt to pay in this checkout");

    Receipt receipt = receiptRepo.save(receiptCreationDTO.dtoToModel());

    checkOut.setLastReceipt(receipt);

    checkOutRepo.save(checkOut);

    return new SuccessMessageDTO("Creation with Success");
}

From source file:ch.bastiangardel.easypay.rest.ReceiptController.java

License:Open Source License

@RequestMapping(value = "/pay", method = POST)
@RequiresAuthentication/*from w ww . j a  va 2s  .c o m*/
public SuccessMessageDTO paiement(@RequestBody ReceiptPayDTO receiptPayDTO, @RequestParam("uuid") String uuid) {
    log.info("PayReceipt : {}", receiptPayDTO.getId());

    final Subject subject = SecurityUtils.getSubject();
    Receipt receipt;

    receipt = receiptRepo.findOne(receiptPayDTO.getId());

    if (receipt == null)
        throw new ReceiptNotFoundException("Not found Receipt with ID : " + receiptPayDTO.getId());

    CheckOut checkOut;

    checkOut = checkOutRepo.findByUuid(uuid);

    if (checkOut == null)
        throw new CheckOutNotFoundException("Not found CheckOut with UUID : " + uuid);

    User owner = checkOut.getOwner();

    if (receipt.isPaid())
        throw new NoReceiptToPayExeption("Receipt with id : " + receipt.getId() + " already pay");

    User user = userRepo.findByEmail((String) subject.getSession().getAttribute("email"));

    if (receipt.getAmount() > user.getAmount())
        throw new NotEnoughMoneyException("You have not enough money in your account!!");

    checkOut.setLastReceipt(null);
    List<Receipt> listreceipt = checkOut.getReceiptsHistory();
    listreceipt.add(receipt);
    receipt.setPaid(true);

    user.setAmount(user.getAmount() - receipt.getAmount());

    receipt.setPaiyedBy(user);

    owner.setAmount(owner.getAmount() + receipt.getAmount());

    List<Receipt> list = user.getReceiptHistory();
    list.add(receipt);

    ApnsService service = APNS.newService().withCert("apns.p12", "sake56ekas").withSandboxDestination().build();

    String payload = APNS.newPayload()
            .alertBody("Receipt " + receipt.getId() + " on checkout " + uuid + " payed by " + user.getName())
            .alertTitle("Receipt Payed").customField("uuid", uuid).build();

    String token = receipt.getDeviceToken();

    if (token != "") {

        log.info("Playload : {}", payload);

        service.push(token, payload);

        log.info("The notification has been hopefully sent");
    }

    userRepo.save(user);
    userRepo.save(owner);
    receiptRepo.save(receipt);
    checkOutRepo.save(checkOut);

    return new SuccessMessageDTO("Payment executed with Success");

}

From source file:ch.bastiangardel.easypay.rest.UserController.java

License:Open Source License

@RequestMapping(value = "/auth", method = POST)
public void authenticate(@RequestBody final CredentialDTO credentials) {

    final Subject subject = SecurityUtils.getSubject();

    log.info("Authenticating {}", credentials.getUsername() + " : " + subject.getSession().getHost());

    subject.login(credentials.daoToModel(subject.getSession().getHost()));
    // set attribute that will allow session querying
    subject.getSession().setAttribute("email", credentials.getUsername());

}

From source file:ch.bastiangardel.easypay.rest.UserController.java

License:Open Source License

@RequestMapping(value = "/logout", method = POST)
@RequiresAuthentication//from  w  ww .j a v  a2 s  .c o  m
public void logout() {

    final Subject subject = SecurityUtils.getSubject();
    log.info("logout {}", subject.getSession().getAttribute("email"));
    subject.logout();
}

From source file:ch.reboundsoft.shinobi.authstore.CachedAuthStoreImpl.java

@Override
public synchronized boolean login(String name, String password) {

    log.info("Login using cached auth store");

    Subject currentUser;//from w  w  w .  j  av a2  s  .co  m

    if (subjects.containsKey(name)) {
        currentUser = subjects.get(name);
    } else {
        currentUser = SecurityUtils.getSubject();
        subjects.put(name, currentUser);
    }

    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);

        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
            return false;
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            return false;
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
            return false;
        } catch (AuthenticationException ae) {
            log.info("Strange auth error: " + ae.toString());
            return false;
        }
    }

    cache.add(getCacheKey(name), password);

    return true;

}

From source file:ch.reboundsoft.shinobi.authstore.DefaultAuthStoreImpl.java

@Override
public synchronized boolean login(String name, String password) {

    log.info("Login using default auth store");

    Subject currentUser;//  w  w w.  j a v  a 2 s .  c  o m

    if (subjects.containsKey(name)) {
        currentUser = subjects.get(name);
    } else {
        currentUser = SecurityUtils.getSubject();
        subjects.put(name, currentUser);
    }

    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);

        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
            return false;
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            return false;
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
            return false;
        } catch (AuthenticationException ae) {
            log.info("Strange auth error: " + ae.toString());
            return false;
        }
    }

    return true;

}

From source file:cn.adfi.radius.controller.LoginController.java

private User loginInner(String username, String password) {
    Subject subject = SecurityUtils.getSubject();
    subject.login(new UsernamePasswordToken(username, password));
    if (subject.isAuthenticated()) {
        List<User> lst = userRepo.findByUsername(username);
        Session session = subject.getSession();
        session.setAttribute("user", lst.get(0));
        return lst.get(0);
    }//from ww  w  .j  a  va 2  s  .c o m
    return null;

}