TokenController.java 3.03 KB
package com.xkl.controller;

import com.xkl.authorization.annotation.Authorization;
import com.xkl.authorization.annotation.CurrentUser;
import com.xkl.authorization.manager.ITokenManager;
import com.xkl.authorization.model.TokenModel;
import com.xkl.config.ResultStatus;
import com.xkl.domain.User;
import com.xkl.model.ResultModel;
import com.xkl.repository.UserRepository;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import com.xkl.security.SecurityTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
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.RestController;

/**
 * 获取和删除token的请求地址,在Restful设计中其实就对应着登录和退出登录的资源映射
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ITokenManager tokenManager;

    @RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "登录")
    public ResponseEntity<ResultModel> login(@RequestParam String username, @RequestParam String password) {
        Assert.notNull(username, "username can not be empty");
        Assert.notNull(password, "password can not be empty");

        User user = userRepository.findByLoginAccount(username);

        if (user == null) {  //用户不存在
            return new ResponseEntity<>(ResultModel.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR), HttpStatus.NOT_FOUND);
        } else {
            String salt = user.getSalt();
            String pass_in_db = user.getLoginPwd();
            String pass = SecurityTool.getPassword(username, password, salt);
            if (!pass.equals(pass_in_db))
                // TODO: 2016/11/26 use pwd with salt
                // if(!password.equals(pass_in_db))  // for test
                return new ResponseEntity<>(ResultModel.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR), HttpStatus.NOT_FOUND);
        }
        //生成一个token,保存用户登录状态
        TokenModel model = tokenManager.createToken(user.getId());
        return new ResponseEntity<>(ResultModel.ok(model), HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    @Authorization
    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "请输入登录返回信息:userId_tokens", required = true, dataType = "string", paramType = "header"),
    })
    public ResponseEntity<ResultModel> logout(@CurrentUser User user) {
        tokenManager.deleteToken(user.getId());
        return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
    }

}