Bläddra i källkod

登录 登出 修改密码

魏熙美 5 år sedan
förälder
incheckning
2ef150293c

+ 8
- 0
foyo-service/pom.xml Visa fil

@@ -62,6 +62,14 @@
62 62
 			<artifactId>pagehelper-spring-boot-starter</artifactId>
63 63
 			<version>1.2.3</version>
64 64
 		</dependency>
65
+
66
+		<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
67
+		<dependency>
68
+			<groupId>commons-codec</groupId>
69
+			<artifactId>commons-codec</artifactId>
70
+			<version>1.13</version>
71
+		</dependency>
72
+
65 73
 	</dependencies>
66 74
 
67 75
 	<build>

+ 3
- 0
foyo-service/src/main/java/com/huiju/foyo/common/BaseController.java Visa fil

@@ -8,4 +8,7 @@ import lombok.extern.slf4j.Slf4j;
8 8
  */
9 9
 @Slf4j
10 10
 public class BaseController {
11
+
12
+
13
+
11 14
 }

+ 27
- 0
foyo-service/src/main/java/com/huiju/foyo/common/Md5Utils.java Visa fil

@@ -0,0 +1,27 @@
1
+package com.huiju.foyo.common;
2
+
3
+import org.apache.commons.codec.digest.DigestUtils;
4
+
5
+public class Md5Utils {
6
+
7
+    public static String encryptionMd5(String str) {
8
+        return DigestUtils.md5Hex(str);
9
+    }
10
+
11
+    /**
12
+     * 密码比对
13
+     * @param encrypPass 已加密
14
+     * @param pass 未加密
15
+     * @return
16
+     */
17
+    public static boolean isMd5ThanPass(String encrypPass, String pass ) {
18
+        String encPass = encryptionMd5(pass);
19
+        return encPass.equals(encrypPass);
20
+    }
21
+
22
+
23
+    public static void main(String[] args) {
24
+        System.out.println(encryptionMd5("123456"));
25
+        System.out.println(isMd5ThanPass("e10adc3949ba59abbe56e057f20f883e", "123456"));
26
+    }
27
+}

+ 59
- 46
foyo-service/src/main/java/com/huiju/foyo/controller/LoginController.java Visa fil

@@ -1,15 +1,19 @@
1 1
 package com.huiju.foyo.controller;
2 2
 
3 3
 import com.alibaba.fastjson.JSONObject;
4
+import com.huiju.foyo.common.BaseController;
5
+import com.huiju.foyo.common.Md5Utils;
4 6
 import com.huiju.foyo.common.ResponseBean;
5 7
 import com.huiju.foyo.model.SysUser;
6 8
 import com.huiju.foyo.service.ISysUserService;
9
+import com.huiju.foyo.session.UserControl;
7 10
 import org.springframework.beans.factory.annotation.Autowired;
8
-import org.springframework.web.bind.annotation.GetMapping;
9
-import org.springframework.web.bind.annotation.PostMapping;
10
-import org.springframework.web.bind.annotation.RequestBody;
11
-import org.springframework.web.bind.annotation.RequestMapping;
12
-import org.springframework.web.bind.annotation.RestController;
11
+import org.springframework.http.HttpStatus;
12
+import org.springframework.web.bind.annotation.*;
13
+
14
+import javax.servlet.http.HttpSession;
15
+import java.util.HashMap;
16
+import java.util.Map;
13 17
 
14 18
 /**
15 19
  * @author FXF
@@ -21,57 +25,66 @@ public class LoginController {
21 25
 
22 26
 	@Autowired
23 27
 	ISysUserService iSysUserService;
24
-	
25
-	@PostMapping("/admin/login/login")
26
-	public ResponseBean login(@RequestBody String jsonString){
27
-		ResponseBean responseBean = new ResponseBean();
28 28
 
29
-		JSONObject params = JSONObject.parseObject(jsonString);
30
-		if (null == params) {
31
-			responseBean.addError("请填写用户名及密码");
32
-			return responseBean;
33
-		}
34
-
35
-		String name = params.getString("name");
36
-		String passed = params.getString("password");
29
+	@RequestMapping("/admin/toLogin")
30
+	public ResponseBean toLogin() {
31
+		ResponseBean responseBean = new ResponseBean();
32
+		responseBean.addError("用户未登录");
33
+		return responseBean;
34
+	}
37 35
 
38
-		if (null == name || "".equals(name.trim()) || null == passed || "".equals(passed.trim())) {
39
-			responseBean.addError("用户名或者密码不正确");
40
-			return responseBean;
41
-		}
36
+	/**
37
+	 * 登录
38
+	 * @param jsonString
39
+	 * @return
40
+	 */
41
+	@PostMapping("/admin/login")
42
+	public ResponseBean login(@RequestBody String jsonString){
43
+		return iSysUserService.login(jsonString);
44
+	}
42 45
 
43
-		SysUser sysUser = iSysUserService.getUserByLoginName(name);
46
+	/**
47
+	 * 退出登录
48
+	 * @return
49
+	 */
50
+	@PostMapping("/admin/logout")
51
+	public ResponseBean logout() {
52
+		UserControl.removeUser();
53
+		return new ResponseBean();
54
+	}
44 55
 
45
-		// 比较密码是否一致
46
-		// todo
56
+	/**
57
+	 * 获取用户信息
58
+	 * @return
59
+	 */
60
+	@GetMapping("/admin/user/info")
61
+	public ResponseBean info(HttpSession session){
62
+		ResponseBean responseBean = new ResponseBean();
47 63
 
48
-		// 生成 session 或者 token
49
-		// todo
64
+		// 判断是否登录
65
+		SysUser user = UserControl.getUser();
50 66
 
51
-		// 返回内容密码为空
52
-		sysUser.setPasswd(null);
67
+		Map<String, Object> map = new HashMap<>();
68
+		map.put("roles","['admin']");
69
+		map.put("token",user.getToken());
70
+		map.put("introduction","我是超级管理员");
71
+		map.put("avatar", user.getAvatar());
72
+		map.put("name", user.getName());
53 73
 
54
-		responseBean.addSuccess(sysUser);
74
+		responseBean.addSuccess(map);
55 75
 		return responseBean;
56 76
 	}
57 77
 
58
-	@PostMapping("/admin/login/logout")
59
-	public ResponseBean logout() {
60
-		// todo
61
-		return new ResponseBean();
62
-	}
63
-	
64
-	@GetMapping("/admin/user/info")
65
-	public String info(){
66
-		// 判断是否登录
67
-		// todo
78
+	/**
79
+	 * 修改密码
80
+	 * @param oldPass
81
+	 * @param newPass
82
+	 * @return
83
+	 */
84
+	@PutMapping("/admin/user/upPass")
85
+	public ResponseBean updatePass(@RequestParam(value = "oldPass") String oldPass,
86
+								   @RequestParam(value = "newPass") String newPass) {
68 87
 
69
-		JSONObject jsonObject = new JSONObject();
70
-		jsonObject.put("roles","['admin']");
71
-		jsonObject.put("token","admin");
72
-		jsonObject.put("introduction","我是超级管理员");
73
-		jsonObject.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
74
-		jsonObject.put("name","'Super Admin'");
75
-		return jsonObject.toJSONString();
88
+		return iSysUserService.upPass(oldPass, newPass);
76 89
 	}
77 90
 }

+ 25
- 0
foyo-service/src/main/java/com/huiju/foyo/exception/ExceptionHandle.java Visa fil

@@ -0,0 +1,25 @@
1
+package com.huiju.foyo.exception;
2
+
3
+import com.huiju.foyo.common.ResponseBean;
4
+import org.springframework.web.bind.annotation.ControllerAdvice;
5
+import org.springframework.web.bind.annotation.ExceptionHandler;
6
+import org.springframework.web.bind.annotation.ResponseStatus;
7
+
8
+@ControllerAdvice
9
+public class ExceptionHandle {
10
+
11
+    @ExceptionHandler(Exception.class)
12
+    public ResponseBean handleError(Exception e){
13
+        ResponseBean responseBean = new ResponseBean();
14
+        responseBean.addError("系统异常");
15
+        return responseBean;
16
+    }
17
+
18
+    @ExceptionHandler(FoyoException.class)
19
+    public ResponseBean handleError(FoyoException e){
20
+        ResponseBean responseBean = new ResponseBean();
21
+        responseBean.addError(e.getMessage());
22
+        return responseBean;
23
+    }
24
+
25
+}

+ 11
- 0
foyo-service/src/main/java/com/huiju/foyo/exception/FoyoException.java Visa fil

@@ -0,0 +1,11 @@
1
+package com.huiju.foyo.exception;
2
+
3
+public class FoyoException extends RuntimeException {
4
+
5
+    public FoyoException(String message) {
6
+        super(message);
7
+    }
8
+
9
+    public FoyoException() {
10
+    }
11
+}

+ 42
- 0
foyo-service/src/main/java/com/huiju/foyo/filter/FoyoFilter.java Visa fil

@@ -0,0 +1,42 @@
1
+package com.huiju.foyo.filter;
2
+
3
+import com.huiju.foyo.model.SysUser;
4
+import com.huiju.foyo.session.SessionLoad;
5
+import com.huiju.foyo.session.UserControl;
6
+import org.springframework.stereotype.Component;
7
+
8
+import javax.servlet.*;
9
+import javax.servlet.http.HttpServletRequest;
10
+import javax.servlet.http.HttpServletResponse;
11
+import java.io.IOException;
12
+
13
+@Component
14
+public class FoyoFilter implements Filter {
15
+
16
+    @Override
17
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
18
+        HttpServletRequest request = (HttpServletRequest) servletRequest;
19
+        HttpServletResponse response = (HttpServletResponse) servletResponse;
20
+
21
+        if (request.getRequestURI().equals("/admin/login")) {
22
+            filterChain.doFilter(servletRequest, servletResponse);
23
+            return;
24
+        }
25
+
26
+        SysUser user = SessionLoad.getUser();
27
+        if (null == user) {
28
+            user = (SysUser) request.getSession().getAttribute(UserControl.SESSION_USER);
29
+            if (null == user) {
30
+                // 重定向登录
31
+                request.getRequestDispatcher("/admin/toLogin").forward(servletRequest, servletResponse);
32
+                return;
33
+            }
34
+        }
35
+
36
+        // 设置用户
37
+        UserControl.setUser(user);
38
+
39
+        // 继续执行
40
+        filterChain.doFilter(servletRequest, servletResponse);
41
+    }
42
+}

+ 8
- 0
foyo-service/src/main/java/com/huiju/foyo/model/SysUser.java Visa fil

@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
5 5
 import com.baomidou.mybatisplus.annotation.TableId;
6 6
 import lombok.Data;
7 7
 import lombok.EqualsAndHashCode;
8
+import lombok.ToString;
8 9
 import lombok.experimental.Accessors;
9 10
 
10 11
 import java.io.Serializable;
@@ -23,6 +24,7 @@ import java.util.List;
23 24
 @Data
24 25
 @EqualsAndHashCode(callSuper = false)
25 26
 @Accessors(chain = true)
27
+@ToString
26 28
 public class SysUser implements Serializable {
27 29
 
28 30
     private static final long serialVersionUID = 1L;
@@ -49,4 +51,10 @@ public class SysUser implements Serializable {
49 51
      */
50 52
     private Integer status;
51 53
 
54
+    /**
55
+     * 用户token
56
+     */
57
+    @TableField(exist = false)
58
+    private String token;
59
+
52 60
 }

+ 21
- 0
foyo-service/src/main/java/com/huiju/foyo/service/ISysUserService.java Visa fil

@@ -1,8 +1,29 @@
1 1
 package com.huiju.foyo.service;
2 2
 
3 3
 import com.baomidou.mybatisplus.extension.service.IService;
4
+import com.huiju.foyo.common.ResponseBean;
4 5
 import com.huiju.foyo.model.SysUser;
5 6
 
6 7
 public interface ISysUserService extends IService<SysUser> {
8
+    /**
9
+     * 根据用户名获取用户信息
10
+     * @param name
11
+     * @return
12
+     */
7 13
     SysUser getUserByLoginName(String name);
14
+
15
+    /**
16
+     * 登录
17
+     * @param jsonString
18
+     * @return
19
+     */
20
+    ResponseBean login(String jsonString);
21
+
22
+    /**
23
+     * 修改密码
24
+     * @param oldPass
25
+     * @param newPass
26
+     * @return
27
+     */
28
+    ResponseBean upPass(String oldPass, String newPass);
8 29
 }

+ 70
- 0
foyo-service/src/main/java/com/huiju/foyo/service/impl/SysUserServiceImpl.java Visa fil

@@ -1,10 +1,16 @@
1 1
 package com.huiju.foyo.service.impl;
2 2
 
3
+import com.alibaba.fastjson.JSONObject;
3 4
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4 5
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
6
+import com.github.pagehelper.util.StringUtil;
7
+import com.huiju.foyo.common.Md5Utils;
8
+import com.huiju.foyo.common.ResponseBean;
9
+import com.huiju.foyo.session.SessionLoad;
5 10
 import com.huiju.foyo.dao.SysUserMapper;
6 11
 import com.huiju.foyo.model.SysUser;
7 12
 import com.huiju.foyo.service.ISysUserService;
13
+import com.huiju.foyo.session.UserControl;
8 14
 import org.springframework.beans.factory.annotation.Autowired;
9 15
 import org.springframework.stereotype.Service;
10 16
 
@@ -30,4 +36,68 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
30 36
 
31 37
         return sysUserMapper.selectOne(wrapper);
32 38
     }
39
+
40
+
41
+    @Override
42
+    public ResponseBean login(String jsonString) {
43
+        ResponseBean responseBean = new ResponseBean();
44
+
45
+        JSONObject params = JSONObject.parseObject(jsonString);
46
+        if (null == params) {
47
+            responseBean.addError("请填写用户名及密码");
48
+            return responseBean;
49
+        }
50
+
51
+        String name = params.getString("username");
52
+        String passed = params.getString("password");
53
+
54
+        if (null == name || "".equals(name.trim()) || null == passed || "".equals(passed.trim())) {
55
+            responseBean.addError("用户名或者密码不正确");
56
+            return responseBean;
57
+        }
58
+
59
+        SysUser sysUser = getUserByLoginName(name);
60
+
61
+        // 比较密码是否一致
62
+        if (!Md5Utils.isMd5ThanPass(sysUser.getPasswd(), passed)){
63
+            responseBean.addError("用户名或者密码不正确");
64
+            return responseBean;
65
+        }
66
+
67
+        // 生成 session 或者 token
68
+        UserControl.setUser(sysUser);
69
+
70
+        // 返回内容密码为空
71
+        sysUser.setPasswd(null);
72
+
73
+        responseBean.addSuccess(sysUser);
74
+        return responseBean;
75
+    }
76
+
77
+    @Override
78
+    public ResponseBean upPass(String oldPass, String newPass) {
79
+        ResponseBean responseBean = new ResponseBean();
80
+
81
+        SysUser sessionUser = UserControl.getUser();
82
+
83
+        // 根据用户名查询最新信息
84
+        SysUser userByLoginName = getUserByLoginName(sessionUser.getName());
85
+        if (!Md5Utils.isMd5ThanPass(userByLoginName.getPasswd(), oldPass)) {
86
+            responseBean.addError("请输入正确的旧密码");
87
+            return responseBean;
88
+        }
89
+
90
+        if (newPass.length() < 6) {
91
+            responseBean.addError("新密码不能小于6位");
92
+            return responseBean;
93
+        }
94
+
95
+        String encryptionMd5 = Md5Utils.encryptionMd5(newPass);
96
+        userByLoginName.setPasswd(encryptionMd5);
97
+
98
+        this.updateById(userByLoginName);
99
+
100
+        responseBean.addSuccess("操作成功");
101
+        return responseBean;
102
+    }
33 103
 }

+ 41
- 0
foyo-service/src/main/java/com/huiju/foyo/session/SessionLoad.java Visa fil

@@ -0,0 +1,41 @@
1
+package com.huiju.foyo.session;
2
+
3
+import com.huiju.foyo.model.SysUser;
4
+import lombok.extern.slf4j.Slf4j;
5
+
6
+/**
7
+ * session 操作
8
+ * @author weiximei
9
+ */
10
+@Slf4j
11
+public class SessionLoad {
12
+
13
+    private static ThreadLocal<SysUser> threadLocal = new ThreadLocal<>();
14
+
15
+    /**
16
+     * 设置用户信息
17
+     * @param user
18
+     */
19
+    public static void setUser(SysUser user){
20
+        log.info("当前线程 --- [{}] --- 设置用户 {} ", Thread.currentThread().getName(), user);
21
+        threadLocal.set(user);
22
+    }
23
+
24
+    /**
25
+     * 获取用户信息
26
+     * @return
27
+     */
28
+    public static SysUser getUser() {
29
+        SysUser user = threadLocal.get();
30
+        log.info("当前线程 --- [{}] --- 获取用户 {} ", Thread.currentThread().getName(), user);
31
+        return user;
32
+    }
33
+
34
+    /**
35
+     * 移除用户
36
+     */
37
+    public static void removeUser() {
38
+        threadLocal.remove();
39
+    }
40
+
41
+}

+ 69
- 0
foyo-service/src/main/java/com/huiju/foyo/session/UserControl.java Visa fil

@@ -0,0 +1,69 @@
1
+package com.huiju.foyo.session;
2
+
3
+import com.huiju.foyo.exception.FoyoException;
4
+import com.huiju.foyo.model.SysUser;
5
+import lombok.extern.slf4j.Slf4j;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.stereotype.Component;
8
+import org.springframework.web.context.request.RequestContextHolder;
9
+import org.springframework.web.context.request.ServletRequestAttributes;
10
+
11
+import javax.servlet.http.HttpSession;
12
+
13
+/**
14
+ * 用户session
15
+ * @author weiximei
16
+ */
17
+@Component
18
+@Slf4j
19
+public class UserControl {
20
+
21
+    public static final String SESSION_USER = "user";
22
+
23
+    /**
24
+     * 设置用户
25
+     * @param user
26
+     */
27
+    public static void setUser(SysUser user) {
28
+        if (null == user) {
29
+            throw new FoyoException("用户信息不能为空");
30
+        }
31
+        HttpSession session = getSession();
32
+        user.setToken(session.getId());
33
+        session.setAttribute(SESSION_USER, user);
34
+        log.info("当前用户sessionId: {}", session.getId());
35
+        SessionLoad.setUser(user);
36
+    }
37
+
38
+    /**
39
+     * 获取当前用户
40
+     * @return
41
+     */
42
+    public static SysUser getUser() {
43
+        HttpSession session = getSession();
44
+        log.info("当前用户sessionId: {}", session.getId());
45
+
46
+        SysUser sysUser = SessionLoad.getUser();
47
+        if (null == sysUser) {
48
+            throw new FoyoException("用户未登录");
49
+        }
50
+
51
+        return sysUser;
52
+    }
53
+
54
+    /**
55
+     * 移除用户
56
+     */
57
+    public static void removeUser() {
58
+        HttpSession session = getSession();
59
+        session.removeAttribute(SESSION_USER);
60
+        log.info("当前用户sessionId: {}, 退出登录", session.getId());
61
+
62
+        SessionLoad.removeUser();
63
+    }
64
+
65
+    private static HttpSession getSession() {
66
+        HttpSession session = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
67
+        return session;
68
+    }
69
+}

+ 15
- 5
vue-element-admin/src/api/login.js Visa fil

@@ -6,7 +6,7 @@ export function loginByUsername(username, password) {
6 6
     password
7 7
   }
8 8
   return request({
9
-    url: '/login/login',
9
+    url: '/login',
10 10
     method: 'post',
11 11
     data
12 12
   })
@@ -14,16 +14,26 @@ export function loginByUsername(username, password) {
14 14
 
15 15
 export function logout() {
16 16
   return request({
17
-    url: '/login/logout',
17
+    url: '/logout',
18 18
     method: 'post'
19 19
   })
20 20
 }
21 21
 
22
-export function getUserInfo(token) {
22
+export function getUserInfo() {
23 23
   return request({
24 24
     url: '/user/info',
25
-    method: 'get',
26
-    params: { token }
25
+    method: 'get'
26
+  })
27
+}
28
+
29
+export function updatePass(data) {
30
+  return request({
31
+    url: '/user/upPass',
32
+    method: 'put',
33
+    params: {
34
+      oldPass: data.oldPass,
35
+      newPass: data.newPass
36
+    }
27 37
   })
28 38
 }
29 39
 

+ 9
- 5
vue-element-admin/src/views/login/index.vue Visa fil

@@ -36,7 +36,7 @@
36 36
         </span>
37 37
       </el-form-item>
38 38
 
39
-      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">{{ $t('login.logIn') }}</el-button>
39
+      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin('loginForm')">{{ $t('login.logIn') }}</el-button>
40 40
 
41 41
     </el-form>
42 42
 
@@ -112,13 +112,17 @@ export default {
112 112
         this.passwordType = 'password'
113 113
       }
114 114
     },
115
-    handleLogin() {
116
-      this.$refs.loginForm.validate(valid => {
115
+    handleLogin(form) {
116
+      this.$refs[form].validate(valid => {
117 117
         if (valid) {
118
-          console.log('222222222222222')
119 118
           this.loading = true
120
-          this.$store.dispatch('LoginByUsername', this.loginForm).then(() => {
119
+          this.$store.dispatch('LoginByUsername', this.loginForm).then((res) => {
121 120
             this.loading = false
121
+            const resCode = res.code
122
+            if (resCode !== '0') {
123
+              this.$message.error(res.message || res.msg)
124
+              return
125
+            }
122 126
             this.$router.push({ path: this.redirect || '/' })
123 127
           }).catch(() => {
124 128
             this.loading = false