com.github.dactiv.fear.user.web.AccountController.java Source code

Java tutorial

Introduction

Here is the source code for com.github.dactiv.fear.user.web.AccountController.java

Source

/*
 * Copyright 2015 dactiv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.dactiv.fear.user.web;

import com.github.dactiv.fear.commons.Apis;
import com.github.dactiv.fear.commons.Casts;
import com.github.dactiv.fear.commons.enumeration.PortraitSize;
import com.github.dactiv.fear.commons.exception.ServiceException;
import com.github.dactiv.fear.commons.service.auth.Subjects;
import com.github.dactiv.fear.user.service.TokenExpiredException;
import com.github.dactiv.fear.user.service.TokenNotFoundException;
import com.github.dactiv.fear.user.service.ValidToken;
import com.github.dactiv.fear.user.service.account.AccountService;
import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.AbstractRememberMeManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 
 *
 * @author maurice
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    private final static Logger LOGGER = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private AccountService accountService;

    /**
     * ???
     *
     * @param username ??
     *
     * @return true ? false
     */
    @ResponseBody
    @RequestMapping("is-username-unique")
    public boolean isUsernameUnique(@RequestParam String username) {
        return Apis.invoke("accountService", "isUsernameUnique", username);
    }

    /**
     * 
     */
    @RequestMapping("user-profile")
    public void userProfile() {

    }

    /**
     * ?
     *
     * @param mail 
     *
     * @return true ? false
     */
    @ResponseBody
    @RequestMapping("is-mail-unique")
    public boolean isMailUnique(@RequestParam String mail) {
        return Apis.invoke("accountService", "isUserEmailUnique", mail);
    }

    /**
     * ??
     *
     * @param oldPassword ?
     * @param newPassword ?
     *
     * @return ??:/WEB-INF/page/login.ftl
     */
    @RequestMapping("update-password")
    public String updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {

        Map<String, Object> user = Subjects.getPrincipal();
        Apis.invoke("accountService", "updateUserPassword", user, oldPassword, newPassword);

        return "redirect:/logout";

    }

    /**
     * ??
     *
     * @param entity  map
     * @param request http servlet request
     *
     * @return ??:WEB-INF/page/index.ftl
     *
     * @throws Exception
     */
    @RequestMapping(value = "registration", method = { RequestMethod.GET, RequestMethod.POST })
    public String registration(@RequestParam Map<String, Object> entity, HttpServletRequest request)
            throws Exception {

        if (request.getMethod().equals(HttpMethod.GET.name())) {
            return "registration";
        } else {

            accountService.registration(entity);

            String username = entity.get("username").toString();
            String password = entity.get("password").toString();
            SecurityUtils.getSubject()
                    .login(new UsernamePasswordToken(username, password, request.getRemoteHost()));
            return "redirect:/account/user-profile";
        }
    }

    /**
     * ?
     *
     * @param id                 id
     * @param redirectAttributes spring mvc ??
     *
     * @return ???:WEB-INF/page/index.ftl???:WEB-INF/page/exception/service-exception.ftl
     */
    @RequestMapping("valid-mail")
    public String validMail(@RequestParam String id, RedirectAttributes redirectAttributes) {

        accountService.validMail(id);
        redirectAttributes.addFlashAttribute("message", "??");

        return "redirect:/account/user-profile";
    }

    /**
     * ???
     *
     * @return ? true ? false
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("send-valid-mail")
    public boolean sendValidMail(String mail) throws Exception {
        Map<String, Object> principal = Subjects.getPrincipal();

        if (principal.get("email").equals(mail)) {
            return Boolean.FALSE;
        }

        try {
            accountService.sendValidMail(mail);
            return Boolean.TRUE;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("???", e);
        }

        return Boolean.FALSE;
    }

    /**
     * ???
     *
     * @param username 
     * @param captcha ??
     * @param request http servlet request
     *
     * @return ??:WEB-INF/page/index.ftl
     *
     * @throws Exception
     */
    @RequestMapping(value = "forgot-password", method = { RequestMethod.GET, RequestMethod.POST })
    public String forgotPassword(String username, String captcha, HttpServletRequest request) throws Exception {
        if (request.getMethod().equals(HttpMethod.GET.name())) {
            return "/forgot-password";
        } else {
            Map<String, Object> user;
            try {
                user = accountService.forgotPassword(username, captcha);
            } catch (ServiceException e) {
                request.setAttribute("message", e.getMessage());
                return "/forgot-password";
            }
            String email = Casts.cast(user.get("email"), String.class);
            request.setAttribute("email", StringUtils.overlay(email, "******", 4, email.indexOf("@")));
            return "reset-password-mail-send";
        }
    }

    /**
     * ??
     *
     * @param id    key
     * @param model spring mvc  Model ?? http servlet request ?
     *
     * @return ??:WEB-INF/page/reset-password.ftl
     */
    @RequestMapping(value = "reset-password", method = RequestMethod.GET)
    public String resetPassword(String id, Model model) {

        try {
            ValidToken validToken = accountService.validForgotPassword(id);
            model.addAttribute("token", validToken.getId());
        } catch (ServiceException e) {
            model.addAttribute("message", e.getMessage());
            return "redirect:forgot-password";
        }

        return "/reset-password";
    }

    /**
     * ??
     *
     * @param token           ?? token
     * @param password        ?
     * @param confirmPassword ?
     * @param model           spring mvc  Model ?? http servlet request ?
     * @param attributes      spring mvc ??
     *
     * @return ????:WEB-INF/page/login.ftl, ???:WEB-INF/page/reset-password.ftl
     */
    @RequestMapping(value = "reset-password", method = RequestMethod.POST)
    public String resetPassword(String token, String password, String confirmPassword, Model model,
            RedirectAttributes attributes) {

        try {
            accountService.resetPassword(token, password, confirmPassword);
        } catch (ServiceException e) {
            if (e instanceof TokenNotFoundException || e instanceof TokenExpiredException) {
                attributes.addFlashAttribute("message", e.getMessage());
                return "redirect:/forgot-password";
            }
            model.addAttribute("message", e.getMessage());
            model.addAttribute("token", token);
            return "/reset-password";
        }

        attributes.addFlashAttribute("message",
                "?????");
        return "redirect:/login";
    }

    /**
     * ?
     *
     * @param request HttpServletRequest http servlet request ? FaustCplus ??
     *
     * @return ? json: {status:"success"}?
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("update-portrait")
    public Map<String, Object> updatePortrait(HttpServletRequest request) throws IOException {
        Map<String, Object> user = Subjects.getPrincipal();
        Apis.invoke("accountService", "updateUserPortrait", user, IOUtils.toByteArray(request.getInputStream()));

        Map<String, Object> result = Maps.newHashMap();
        // ? FaustCplus ?? jsfunc  js 
        result.put("state", Boolean.TRUE);
        result.put("message", "??");

        return result;
    }

    /**
     * ???
     *
     * @return ? byte 
     *
     * @throws java.io.IOException
     */
    @RequestMapping("get-portrait")
    public ResponseEntity<byte[]> getUserPortrait(@RequestParam(required = false) String name,
            @RequestParam(required = false) Integer userId) throws IOException {

        String temp = name;

        if (StringUtils.isEmpty(temp)) {
            temp = PortraitSize.MIDDLE.getName();
        }

        PortraitSize size = PortraitSize.getPortraitSize(temp);

        byte[] bytes;

        if (userId != null) {
            bytes = Apis.invoke("accountService", "getUserPortrait", userId, size);
        } else {
            bytes = Apis.invoke("accountService", "getUserPortrait", Subjects.getPrincipal(), size);
        }

        return new ResponseEntity<>(bytes, HttpStatus.OK);

    }

    /**
     * ?
     *
     * @param entity              Map
     * @param redirectAttributes spring mvc ??
     *
     * @return ? json
     *
     * @throws IOException
     */
    @RequestMapping("update-profile")
    public String updateProfile(@RequestParam Map<String, Object> entity, RedirectAttributes redirectAttributes)
            throws IOException {
        // ?? shiro subject ?
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> user = Casts.cast(subject.getPrincipal());
        // ???
        user.putAll(entity);
        // ??
        Apis.invoke("accountService", "saveUser", user, null);

        DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
        // ?????
        AbstractRememberMeManager rmm = (AbstractRememberMeManager) securityManager.getRememberMeManager();
        rmm.rememberIdentity(subject, null,
                new SimpleAuthenticationInfo(subject.getPrincipals(), user.get("password")));

        // ? subjectDao, ???
        securityManager.getSubjectDAO().save(subject);

        redirectAttributes.addFlashAttribute("message", "??.");

        return "redirect:/account/user-profile";
    }
}