Search in sources :

Example 11 with User

use of com.zyd.blog.business.entity.User in project OneBlog by zhangyd-c.

the class OAuthController method renderAuth.

@RequestMapping("/social/{source}")
public ModelAndView renderAuth(@PathVariable("source") String source, HttpServletResponse response, HttpServletRequest request) {
    SocialConfig socialConfig = sysSocialConfigService.getByPlatform(source);
    if (null == socialConfig) {
        throw new ZhydException(source + " 平台的配置尚未完成,暂时不支持登录!");
    }
    SocialStrategy socialStrategy = new SocialStrategy(japUserService, new JapConfig());
    JapResponse japResponse = socialStrategy.authenticate(JapUtil.blogSocialConfig2JapSocialConfig(socialConfig, source), request, response);
    if (!japResponse.isSuccess()) {
        throw new ZhydException(japResponse.getMessage());
    }
    if (japResponse.isRedirectUrl()) {
        return ResultUtil.redirect((String) japResponse.getData());
    } else {
        JapUser japUser = (JapUser) japResponse.getData();
        User user = (User) japUser.getAdditional();
        SessionUtil.setUser(user);
        return ResultUtil.redirect("/");
    }
}
Also used : ZhydException(com.zyd.blog.framework.exception.ZhydException) JapUser(com.fujieid.jap.core.JapUser) JapConfig(com.fujieid.jap.core.config.JapConfig) User(com.zyd.blog.business.entity.User) JapUser(com.fujieid.jap.core.JapUser) SocialStrategy(com.fujieid.jap.social.SocialStrategy) JapResponse(com.fujieid.jap.core.result.JapResponse) SocialConfig(com.zyd.blog.business.entity.SocialConfig) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 12 with User

use of com.zyd.blog.business.entity.User in project OneBlog by zhangyd-c.

the class JapSocialUserServiceImpl method createAndGetSocialUser.

/**
 * Save the social login user information to the database and return JapUser
 * <p>
 * It is suitable for the {@code jap-social} module
 *
 * @param userInfo User information obtained through justauth third-party login, type {@code me.zhyd.oauth.model.AuthUser}
 * @return When saving successfully, return {@code JapUser}, otherwise return {@code null}
 */
@Override
public JapUser createAndGetSocialUser(Object userInfo) {
    AuthUser authUser = (AuthUser) userInfo;
    User newUser = BeanConvertUtil.doConvert(authUser, User.class);
    newUser.setSource(authUser.getSource());
    if (null != authUser.getGender()) {
        newUser.setGender(Integer.valueOf(authUser.getGender().getCode()));
    }
    User user = userService.getByUuidAndSource(authUser.getUuid(), authUser.getSource());
    newUser.setUserType(UserTypeEnum.USER);
    if (null != user) {
        newUser.setId(user.getId());
        userService.updateSelective(newUser);
    } else {
        userService.insert(newUser);
    }
    try {
        userService.updateUserLastLoginInfo(user);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new JapUser().setUserId(newUser.getId() + "").setUsername(newUser.getUsername()).setAdditional(newUser);
}
Also used : JapUser(com.fujieid.jap.core.JapUser) AuthUser(me.zhyd.oauth.model.AuthUser) User(com.zyd.blog.business.entity.User) JapUser(com.fujieid.jap.core.JapUser) AuthUser(me.zhyd.oauth.model.AuthUser)

Example 13 with User

use of com.zyd.blog.business.entity.User in project OneBlog by zhangyd-c.

the class RemoverServiceImpl method saveArticles.

private void saveArticles(Long typeId, HunterConfig config, HunterPrintWriter writerUtil, CopyOnWriteArrayList<VirtualArticle> list) {
    // 获取数据库中的标签列表
    List<Tags> tags = tagsService.listAll();
    Map<String, Long> originalTags = tags.stream().collect(Collectors.toMap(tag -> tag.getName().toUpperCase(), Tags::getId));
    User user = SessionUtil.getUser();
    // 添加文章到数据库
    Article article = null;
    for (VirtualArticle spiderVirtualArticle : list) {
        article = this.saveArticle(typeId, config.isConvertImg(), writerUtil, user, spiderVirtualArticle);
        this.saveTags(writerUtil, originalTags, article, spiderVirtualArticle);
    }
}
Also used : ArticleStatusEnum(com.zyd.blog.business.enums.ArticleStatusEnum) java.util(java.util) User(com.zyd.blog.business.entity.User) Autowired(org.springframework.beans.factory.annotation.Autowired) Hunter(me.zhyd.hunter.Hunter) HunterConfig(me.zhyd.hunter.config.HunterConfig) Service(org.springframework.stereotype.Service) BizTagsService(com.zyd.blog.business.service.BizTagsService) BizArticleService(com.zyd.blog.business.service.BizArticleService) PrintWriter(java.io.PrintWriter) Validated(org.springframework.validation.annotation.Validated) SessionUtil(com.zyd.blog.util.SessionUtil) ImageLink(me.zhyd.hunter.entity.ImageLink) HunterPrintWriter(me.zhyd.hunter.util.HunterPrintWriter) BlogHunterProcessor(me.zhyd.hunter.processor.BlogHunterProcessor) Article(com.zyd.blog.business.entity.Article) Collectors(java.util.stream.Collectors) VirtualArticle(me.zhyd.hunter.entity.VirtualArticle) BizArticleTagsService(com.zyd.blog.business.service.BizArticleTagsService) RemoverService(com.zyd.blog.business.service.RemoverService) Tags(com.zyd.blog.business.entity.Tags) ImageDownloadUtil(com.zyd.blog.business.util.ImageDownloadUtil) CollectionUtils(org.springframework.util.CollectionUtils) HunterProcessor(me.zhyd.hunter.processor.HunterProcessor) Transactional(org.springframework.transaction.annotation.Transactional) StringUtils(org.springframework.util.StringUtils) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) VirtualArticle(me.zhyd.hunter.entity.VirtualArticle) User(com.zyd.blog.business.entity.User) Article(com.zyd.blog.business.entity.Article) VirtualArticle(me.zhyd.hunter.entity.VirtualArticle) Tags(com.zyd.blog.business.entity.Tags)

Example 14 with User

use of com.zyd.blog.business.entity.User in project OneBlog by zhangyd-c.

the class RememberAuthenticationInterceptor method preHandle.

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    if (subject.isAuthenticated()) {
        return true;
    }
    Session session = subject.getSession(true);
    if (session.getAttribute(SessionConst.USER_SESSION_KEY) != null) {
        return true;
    }
    if (!subject.isRemembered()) {
        log.warn("未设置“记住我”,跳转到登录页...");
        response.sendRedirect(request.getContextPath() + "/passport/login");
        return false;
    }
    try {
        Long userId = Long.parseLong(subject.getPrincipal().toString());
        User user = userService.getByPrimaryKey(userId);
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), PasswordUtil.decrypt(user.getPassword(), user.getUsername()), true);
        subject.login(token);
        session.setAttribute(SessionConst.USER_SESSION_KEY, user);
        log.info("[{}] - 已自动登录", user.getUsername());
    } catch (Exception e) {
        log.error("自动登录失败", e);
        response.sendRedirect(request.getContextPath() + "/passport/login");
        return false;
    }
    return true;
}
Also used : User(com.zyd.blog.business.entity.User) Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken)

Example 15 with User

use of com.zyd.blog.business.entity.User in project OneBlog by zhangyd-c.

the class RetryLimitCredentialsMatcher method doCredentialsMatch.

@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    Long userId = (Long) info.getPrincipals().getPrimaryPrincipal();
    User user = userService.getByPrimaryKey(userId);
    String username = user.getUsername();
    // 访问一次,计数一次
    ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
    String loginCountKey = SHIRO_LOGIN_COUNT + username;
    String isLockKey = SHIRO_IS_LOCK + username;
    opsForValue.increment(loginCountKey, 1);
    if (redisTemplate.hasKey(isLockKey)) {
        String unit = "分钟";
        long time = TimeUnit.SECONDS.toMinutes(redisTemplate.getExpire(isLockKey));
        if (time <= 0) {
            unit = "秒";
            time = TimeUnit.SECONDS.toSeconds(redisTemplate.getExpire(isLockKey));
        } else if (time > 60) {
            unit = "小时";
            time = TimeUnit.SECONDS.toHours(redisTemplate.getExpire(isLockKey));
        }
        throw new ExcessiveAttemptsException("帐号[" + username + "]已被禁止登录!剩余" + time + unit);
    }
    Map<String, Object> configs = configService.getConfigs();
    Object loginRetryNumObj = configs.get("loginRetryNum");
    Object sessionTimeOutObj = configs.get("sessionTimeOut");
    Object sessionTimeOutUnitObj = configs.get("sessionTimeOutUnit");
    int loginRetryNum = StringUtils.isEmpty(loginRetryNumObj) ? DEFAULT_RETRY_NUM : Integer.parseInt(String.valueOf(loginRetryNumObj));
    int sessionTimeOut = StringUtils.isEmpty(sessionTimeOutObj) ? DEFAULT_SESSIONTIME_OUT : Integer.parseInt(String.valueOf(sessionTimeOutObj));
    TimeUnit sessionTimeOutUnit = StringUtils.isEmpty(sessionTimeOutUnitObj) ? DEFAULT_SESSIONTIME_OUT_UNIT : TimeUnit.valueOf(String.valueOf(sessionTimeOutUnitObj));
    String loginCount = String.valueOf(opsForValue.get(loginCountKey));
    int retryCount = ((loginRetryNum + 1) - Integer.parseInt(loginCount));
    if (retryCount <= 0) {
        opsForValue.set(isLockKey, "LOCK");
        redisTemplate.expire(isLockKey, sessionTimeOut, sessionTimeOutUnit);
        redisTemplate.expire(loginCountKey, sessionTimeOut, sessionTimeOutUnit);
        throw new ExcessiveAttemptsException("由于密码输入错误次数过多,帐号[" + username + "]已被禁止登录!");
    }
    boolean matches = super.doCredentialsMatch(token, info);
    if (!matches) {
        throw new AccountException("帐号或密码不正确!您还剩" + retryCount + "次重试的机会");
    }
    // 清空登录计数
    redisTemplate.delete(loginCountKey);
    try {
        userService.updateUserLastLoginInfo(user);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 当验证都通过后,把用户信息放在session里
    // 注:User必须实现序列化
    SecurityUtils.getSubject().getSession().setAttribute(SessionConst.USER_SESSION_KEY, user);
    return true;
}
Also used : User(com.zyd.blog.business.entity.User) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) AccountException(org.apache.shiro.authc.AccountException) ExcessiveAttemptsException(org.apache.shiro.authc.ExcessiveAttemptsException) AccountException(org.apache.shiro.authc.AccountException) TimeUnit(java.util.concurrent.TimeUnit)

Aggregations

User (com.zyd.blog.business.entity.User)24 SysUser (com.zyd.blog.persistence.beans.SysUser)8 ArrayList (java.util.ArrayList)4 BussinessLog (com.zyd.blog.business.annotation.BussinessLog)3 ZhydException (com.zyd.blog.framework.exception.ZhydException)3 JapUser (com.fujieid.jap.core.JapUser)2 RedisCache (com.zyd.blog.business.annotation.RedisCache)2 Article (com.zyd.blog.business.entity.Article)2 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)2 PostMapping (org.springframework.web.bind.annotation.PostMapping)2 JapConfig (com.fujieid.jap.core.config.JapConfig)1 JapResponse (com.fujieid.jap.core.result.JapResponse)1 SocialStrategy (com.fujieid.jap.social.SocialStrategy)1 PageInfo (com.github.pagehelper.PageInfo)1 File (com.zyd.blog.business.entity.File)1 Log (com.zyd.blog.business.entity.Log)1 Resources (com.zyd.blog.business.entity.Resources)1 Role (com.zyd.blog.business.entity.Role)1 SocialConfig (com.zyd.blog.business.entity.SocialConfig)1 Tags (com.zyd.blog.business.entity.Tags)1