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:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * -?// ww  w  .  j ava 2s  . c o  m
 *
 * @return ?-?
 * @version 0.0.1-SNAPSHOT
 * @author -?
 */
@RequestMapping(value = "/articles", method = RequestMethod.GET)
public ModelAndView refurlArticles(@RequestParam(defaultValue = "1") String now_page,
        HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    Subject current_user = SecurityUtils.getSubject();
    if (current_user != null) {
        User user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
        if (user != null) {
            mav.addObject("user", user);
            int rows = 20;
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userId", user.getId());
            param.put("offrow", (StringUtil.getInt(now_page, 1) - 1) * rows);
            param.put("rows", rows);

            List<Article> articles = articleService.getArticleByUserId(param);
            int total = articleService.countArticleRows(param);
            Pagination pagination = new Pagination(StringUtil.getInt(now_page, 1), rows, 5, total,
                    request.getContextPath().concat("/articles"), "0000");

            mav.addObject("pagination", pagination);
            mav.addObject("articles", articles);
            mav.setViewName("user/articles");
        } else {
            mav.setViewName("user/signin");
        }
    } else {
        mav.setViewName("user/signin");
    }
    return mav;
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ??session???//from  w w  w .j av a2s  .co  m
 *
 * @param model
 * @return ??
 * @version 0.0.1-SNAPSHOT
 * @author ?-?
 */
@RequiresAuthentication
@RequestMapping(value = "/update", method = RequestMethod.GET)
public String refurlUpdate(Model model) {
    Subject current_user = SecurityUtils.getSubject();
    User user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
    if (user != null) {
        User u = userService.loadByAccount(user.getAccount());
        model.addAttribute("user", u);
        return "user/update";
    }
    return "redirect:/user/center";
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ???? session???//from   w  w w.  jav  a2  s  . c  o m
 *
 * @param model
 * @param session
 * @return ??
 * @version 0.0.1-SNAPSHOT
 * @author ?
 */
@RequiresAuthentication
@RequestMapping(value = "/updatePassword", method = RequestMethod.GET)
public String updatePassword(Model model, HttpSession session) {
    User user = null;
    Subject current_user = SecurityUtils.getSubject();
    user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
    if (user == null || user.getId() <= 0) {
        user = userService.loadByAccount(current_user.getPrincipal().toString());
    }
    model.addAttribute("user", user);
    return "user/updatePassword";
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ???photo/*from  w  ww . j a v  a 2 s  . co  m*/
 *
 * @param request
 * @return
 * @author -?
 * @version 0.0.1-SNAPSHOT
 */
@RequiresAuthentication
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
@ResponseBody
public String uploadImg(HttpServletRequest request) {
    String msg = "fail";
    User user = null;
    Subject current_user = SecurityUtils.getSubject();
    user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
    if (user == null || user.getId() <= 0) {
        user = userService.loadByAccount(current_user.getPrincipal().toString());
    }
    String path = request.getSession().getServletContext().getRealPath("/static/upload/") + "/photos/"
            + user.getId() + ".jpg";
    File file = new File(path);
    try {
        if (file.exists())
            file.delete();
        else
            file.createNewFile();
        FileUtils.copyInputStreamToFile(request.getInputStream(), file);
        msg = "success";
        log.debug(user.getAccount() + "Path modified image=" + path);
    } catch (IOException e) {
        throw new InternalException(log, "file path=" + path, e);
    }
    log.debug(msg + "," + user.getAccount());
    return msg + "," + user.getAccount();
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ?/*  w w w.j  a v  a2s .c o  m*/
 * <ol>
 * <li>???</li>
 * </ol>
 *
 * @return ???
 * @version 0.0.1-SNAPSHOT
 * @author -?
 */
@RequiresAuthentication
@RequestMapping(value = "/share", method = RequestMethod.GET)
public String refurlShare() {
    Subject current_user = SecurityUtils.getSubject();
    User user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
    if (user != null) {
        return "user/share";
    }
    return "redirect:/user/signin";
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ?/*from   ww w  .j  a  v  a 2 s  .  c  o  m*/
 * <ol>
 * <li>???</li>
 * </ol>
 *
 * @return
 * @version 0.0.1-SNAPSHOT
 * @author -?
 */
@RequiresAuthentication
@Transactional
@RequestMapping(value = "/share", method = RequestMethod.POST)
public @ResponseBody RespMsg share(Article article, @RequestParam String label) {
    RespMsg respMsg = new RespMsg();
    if (article != null && StringUtil.hasText(article.getTitle()) && StringUtil.hasText(article.getContent())) {
        // ???
        Subject current_user = SecurityUtils.getSubject();
        User um = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
        respMsg.setAppendInfo(um.getAccount());
        // ??
        article.setUserId(um.getId());
        // ?
        articleService.addArticle(article);

        // ?
        if (StringUtil.hasText(label)) {
            String labels[] = label.split(",");
            if (labels != null && labels.length > 0) {
                // ?55???
                int lng = (labels.length > 5) ? 5 : labels.length;
                // ????
                for (int i = 0; i < lng; i++) {
                    int label_id = 0;
                    // ?????.
                    Label l = new Label();
                    l.setName(labels[i].trim());
                    List<Label> list = labelService.getLabelByCondition(l);
                    if (list.size() > 0) {
                        label_id = list.get(0).getId();
                    } else { // ???
                        Label l2 = new Label();
                        l2.setUserId(um.getId());
                        l2.setName(labels[i].trim());
                        l2.setPostDate(DateUtil.getNowDateTimeStr(null));
                        labelService.saveLabel(l2);
                        label_id = l2.getId();
                    }
                    // ??
                    ArticleLabel asm = new ArticleLabel();
                    asm.setArticleId(article.getId());
                    asm.setLabelId(label_id);
                    asm.setUserId(um.getId());
                    articleService.saveArticleLabel(asm);
                }
            } else {
                log.warn("The article label format is not correct.");
                respMsg.setStatus("2001");
                respMsg.setMessage(ConfigPool.getString("respMsg.article.ArticlesLabelsCanotEmpty"));
            }
        } else {
            log.warn("The article label can't be empty.");
            respMsg.setStatus("2000");
            respMsg.setMessage(ConfigPool.getString("respMsg.article.ArticlesLabelsCanotEmpty"));
        }
    } else {
        log.warn("Article is a null value.");
        respMsg.setStatus("1000");
        respMsg.setMessage(ConfigPool.getString("respMsg.article.ArticlesCanotEmpty"));
    }
    return respMsg;
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ?//from  ww  w  .j  a  va 2 s.  c o m
 *
 * @param comment_model
 * @return
 * @version 0.0.2-SNAPSHOT
 * @author -?-?
 */
@RequiresAuthentication
@Transactional
@RequestMapping(value = "/comment", method = RequestMethod.POST)
public String comment(Comment comment_model, @RequestParam String article_user_id) {
    if (StringUtil.hasText(comment_model.getContent())) {
        Subject current_user = SecurityUtils.getSubject();
        User user_model = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
        if (user_model != null && user_model.getId() > 0
                && !article_user_id.equals(String.valueOf(user_model.getId()))) {
            comment_model.setUserId(user_model.getId());
            comment_model.setType(1);
            commentService.addComment(comment_model);
            return "redirect:/article/" + comment_model.getObjId();
        }
    }
    return "redirect:/articles";
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ?<br>//from   www . j  a  va  2  s .  c  o  m
 * ?????
 *
 * @return ???
 * @version 0.0.1-SNAPSHOT
 * @author -?
 */
@RequiresAuthentication
@RequestMapping(value = "/emailskip/{account}")
public String emailApprove(Model model) {
    // 1??
    Template template = templateService.loadByName("certifiedMail");
    String str = template.getContent();
    // 2????
    Subject current_user = SecurityUtils.getSubject();
    User user_model = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
    String url = templateService.generateAuthURL(user_model.getAccount());
    // 3???
    str = str.replaceAll("#account#", user_model.getAccount());
    str = str.replaceAll("#url#", url);
    template.setContent(str);
    // 4???
    mailService.sendMail(user_model.getEmail(), template);
    return "user/emailskip";
}

From source file:cn.itganhuo.app.web.controller.UserController.java

License:Apache License

/**
 * ???/*  w  w  w  .j a  v a  2s.c o  m*/
 *
 * @param model ??
 * @return
 */
@RequestMapping(value = "/dynamicArticles", method = RequestMethod.GET)
public String refurlDynamicArticles(Model model, @RequestParam(defaultValue = "1") String now_page,
        HttpServletRequest request) {
    Subject current_user = SecurityUtils.getSubject();
    User user_model = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID);
    if (user_model != null) {
        int rows = 20;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", user_model.getId());
        param.put("offrow", (StringUtil.getInt(now_page, 1) - 1) * rows);
        param.put("rows", rows);
        // ??5
        List<Article> dynamicArticles = articleService.getDynamicArticleByUserId(param);
        int total = articleService.countDynamicArticleRows(param);
        Pagination pagination = new Pagination(StringUtil.getInt(now_page, 1), rows, 5, total,
                request.getContextPath().concat("/dynamicArticles"), now_page);
        model.addAttribute("pagination", pagination);
        model.addAttribute("articles", dynamicArticles);
        model.addAttribute("user", user_model);
        return "user/dynamic_articles";
    } else {
        return "redirect:/user/signin";
    }
}

From source file:cn.ligoo.part.service.shiro.CustomAuthorizingRealm.java

License:Apache License

/**
 * ?, ???.//  ww  w.  ja va 2s .  co m
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    logger.debug("...CustomAuthorizingRealm.doGetAuthorizationInfo()");
    ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
    Assert.notNull(shiroUser, "?principalsshiroUser");

    UserInfo user = userInfoService.findByEmail(shiroUser.email);
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    logger.debug("...add role admin");
    info.addRole("admin");

    SecurityUtils.getSubject().getSession().setAttribute(Constants.SESSION_USER_INFO, user);
    return info;
}