add login module

pangu
PeterAlbus 3 years ago
parent 8bd640b8b0
commit b5c12d5e13

@ -44,7 +44,21 @@
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Sa-Token 权限认证, 在线文档http://sa-token.dev33.cn/ -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.29.0</version>
</dependency>
<!-- Sa-Token 整合 Redis 使用jackson序列化方式 -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis-jackson</artifactId>
<version>1.29.0</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>

@ -1,5 +1,6 @@
package com.peteralbus;
import cn.dev33.satoken.SaManager;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
@ -9,9 +10,17 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
/**
* The type Blog back application.
*/
@SpringBootApplication
public class BlogBackApplication
{
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args)
{
SpringApplication.run(BlogBackApplication.class, args);

@ -0,0 +1,69 @@
package com.peteralbus.config;
import java.util.ArrayList;
import java.util.List;
import com.peteralbus.domain.User;
import com.peteralbus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.dev33.satoken.stp.StpInterface;
/**
*
*
* @author PeterAlbus
*/
@Component
public class StpInterfaceImpl implements StpInterface
{
UserService userService;
@Autowired
public void setUserService(UserService userService)
{
this.userService = userService;
}
/**
*
*/
@Override
public List<String> getPermissionList(Object loginId, String loginType)
{
User user=userService.getUserById(Long.valueOf((String) loginId));
List<String> list = new ArrayList<String>();
if(user.getUserIdentity()<=0)
{
list.add("user-management");
list.add("write-article");
list.add("modify-article");
}
if(user.getUserIdentity()<=5)
{
list.add("comment");
}
return list;
}
/**
* ()
*/
@Override
public List<String> getRoleList(Object loginId, String loginType)
{
User user=userService.getUserById(Long.valueOf((String) loginId));
List<String> list = new ArrayList<String>();
if(user.getUserIdentity()==0)
{
list.add("admin");
}
if(user.getUserIdentity()==5)
{
list.add("user");
}
return list;
}
}

@ -1,7 +1,10 @@
package com.peteralbus.controller;
import cn.dev33.satoken.stp.StpUtil;
import com.peteralbus.domain.Blog;
import com.peteralbus.service.BlogService;
import com.peteralbus.util.RedisUtils;
import com.peteralbus.util.TypeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -12,12 +15,13 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* The type Blog controller.
* @author PeterAlbus
* Created on 2021/7/20.
*
* @author PeterAlbus Created on 2021/7/20.
*/
@RestController
@CrossOrigin
@ -27,6 +31,21 @@ public class BlogController
* The Blog service.
*/
BlogService blogService;
/**
* The Redis utils.
*/
RedisUtils redisUtils;
/**
* Sets redis utils.
*
* @param redisUtils the redis utils
*/
@Autowired
public void setRedisUtils(RedisUtils redisUtils)
{
this.redisUtils = redisUtils;
}
/**
* Sets blog service.
@ -71,6 +90,11 @@ public class BlogController
@PostMapping("/add")
public String add(Blog blog)
{
final String writeArticle="write-article";
if(!StpUtil.hasPermission(writeArticle))
{
return "noPermission";
}
int status;
status=blogService.add(blog);
if(status>0)
@ -92,6 +116,11 @@ public class BlogController
@PostMapping("/update")
public String update(Blog blog)
{
final String modifyArticle="modify-article";
if(!StpUtil.hasPermission(modifyArticle))
{
return "noPermission";
}
int status;
status=blogService.update(blog);
if(status>0)
@ -104,6 +133,28 @@ public class BlogController
}
}
/**
* Visit blog string.
*
* @param blogId the blog id
* @param ipAddress the ip address
* @return the string
*/
@GetMapping("/visitBlog")
public String visitBlog(Long blogId,String ipAddress)
{
String key="blogVisitRecord:"+blogId.toString()+"-"+ipAddress;
if(redisUtils.exists(key))
{
return "repeatVisit";
}
Blog blog=blogService.queryById(blogId);
blog.setBlogViews(blog.getBlogViews()+1);
blogService.update(blog);
redisUtils.set(key, "visited", 8L,TimeUnit.HOURS);
return "success";
}
/**
* Upload string.
*
@ -116,23 +167,11 @@ public class BlogController
String uploadPath="/home/PeterAlbus/assets/blog/imgs/cover/";
String fileName = file.getOriginalFilename();
String type="unknown";
final Set<String> allowTypes = new HashSet<String>(){{
add(".jpg");
add(".jpeg");
add(".png");
add(".JPG");
add(".JPEG");
add(".PNG");
add(".webp");
add(".tif");
add(".WEBP");
add(".TIF");
}};
if(fileName!=null)
{
type=fileName.substring(fileName.lastIndexOf('.'));
}
if(allowTypes.contains(type))
if(TypeUtil.isImg(type))
{
String newName= UUID.randomUUID().toString().replace("-", "").toLowerCase()+type;
File dest = new File(uploadPath + newName);

@ -0,0 +1,80 @@
package com.peteralbus.controller;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.peteralbus.domain.User;
import com.peteralbus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* The type User controller.
* @author PeterAlbus
*/
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController
{
UserService userService;
@Autowired
public void setUserService(UserService userService)
{
this.userService = userService;
}
@RequestMapping("/mailLogin")
public SaTokenInfo doLogin(String userMail, String userPassword)
{
User user=userService.authByMail(userMail, userPassword);
if(user!=null)
{
StpUtil.login(user.getUserId());
return StpUtil.getTokenInfo();
}
return null;
}
@RequestMapping("/isLogin")
public User isLogin()
{
if(StpUtil.isLogin())
{
Long userId=Long.valueOf((String) StpUtil.getLoginId());
return userService.getUserById(userId);
}
return null;
}
@RequestMapping("/logout")
public String logout()
{
StpUtil.logout();
return "logout";
}
@RequestMapping("/register")
public String register(User user)
{
return userService.register(user);
}
@RequestMapping("/changePassword")
public String changePassword(Long userId,String oldPassword,String newPassword)
{
int result=userService.changePassword(userId,oldPassword,newPassword);
if(result==-1)
{
return "wrongPassword";
}
if(result==0)
{
return "error";
}
StpUtil.logout(userId);
return "success";
}
}

@ -9,6 +9,7 @@ import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
/**
* The type Photo.
* @author PeterAlbus

@ -0,0 +1,39 @@
package com.peteralbus.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* The type User.
* @author PeterAlbus
* Created on 2022/3/26.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User implements Serializable
{
@TableId(type= IdType.ASSIGN_ID)
@JsonFormat(shape = JsonFormat.Shape.STRING)
Long userId;
String userUsername;
String userPassword;
String userPhone;
String userMail;
Integer userIdentity;
String userAvatar;
String userSalt;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
LocalDateTime gmtCreate;
}

@ -0,0 +1,15 @@
package com.peteralbus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.peteralbus.domain.User;
import org.apache.ibatis.annotations.Mapper;
/**
* The interface User mapper.
* @author PeterAlbus
* Created on 2022/3/26
*/
@Mapper
public interface UserMapper extends BaseMapper<User>
{
}

@ -0,0 +1,64 @@
package com.peteralbus.service;
import com.peteralbus.domain.User;
/**
* The interface User service.
*
* @author PeterAlbus Created 2022/3/26.
*/
public interface UserService
{
/**
* Register long.
*
* @param user the user
* @return the string
*/
String register(User user);
/**
* Gets user by id.
*
* @param userId the user id
* @return the user by id
*/
User getUserById(Long userId);
/**
* Auth by mail user.
*
* @param userMail the user mail
* @param password the password
* @return the user
*/
User authByMail(String userMail,String password);
/**
* Auth by phone user.
*
* @param userPhone the user phone
* @param password the password
* @return the user
*/
User authByPhone(String userPhone,String password);
/**
* Update user int.
*
* @param user the user
* @return the int
*/
int updateUser(User user);
/**
* Change password int.
*
* @param userId the user id
* @param oldPassword the old password
* @param newPassword the new password
* @return the int
*/
int changePassword(Long userId,String oldPassword,String newPassword);
}

@ -0,0 +1,108 @@
package com.peteralbus.service.impl;
import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peteralbus.domain.User;
import com.peteralbus.mapper.UserMapper;
import com.peteralbus.service.UserService;
import com.peteralbus.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLNonTransientException;
import java.time.LocalDateTime;
/**
* The type Photo service.
* @author PeterAlbus
* Created on 2022/3/26.
*/
@Service
public class UserServiceImpl implements UserService
{
UserMapper userMapper;
@Autowired
public void setUserMapper(UserMapper userMapper)
{
this.userMapper = userMapper;
}
@Override
public String register(User user)
{
user.setGmtCreate(LocalDateTime.now());
user.setUserSalt(Md5Util.getSalt(8));
user.setUserPassword(SaSecureUtil.md5BySalt(user.getUserPassword(), user.getUserSalt()));
try
{
if(userMapper.insert(user)>0)
{
return user.getUserId().toString();
}
}
catch (Exception e)
{
Throwable cause = e.getCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
String sqlState = ((SQLIntegrityConstraintViolationException) cause).getSQLState();
return "repeatAccount";
} else {
e.printStackTrace();
}
}
return null;
}
@Override
public User getUserById(Long userId)
{
return userMapper.selectById(userId);
}
@Override
public User authByMail(String userMail, String userPassword)
{
QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
userQueryWrapper.eq("user_mail",userMail);
User user=userMapper.selectOne(userQueryWrapper);
if(user.getUserPassword().equals(SaSecureUtil.md5BySalt(userPassword, user.getUserSalt())))
{
return user;
}
return null;
}
@Override
public User authByPhone(String userPhone, String userPassword)
{
QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
userQueryWrapper.eq("user_phone",userPhone);
User user=userMapper.selectOne(userQueryWrapper);
if(user.getUserPassword().equals(SaSecureUtil.md5BySalt(userPassword, user.getUserSalt())))
{
return user;
}
return null;
}
@Override
public int updateUser(User user)
{
return userMapper.updateById(user);
}
@Override
public int changePassword(Long userId, String oldPassword, String newPassword)
{
User user=userMapper.selectById(userId);
if(user.getUserPassword().equals(SaSecureUtil.md5BySalt(oldPassword, user.getUserSalt())))
{
user.setUserPassword(SaSecureUtil.md5BySalt(newPassword, user.getUserSalt()));
return userMapper.updateById(user);
}
return -1;
}
}

@ -0,0 +1,28 @@
package com.peteralbus.util;
import java.util.Random;
/**
* The type Md 5 util.
* @author PeterAlbus
* Created on 2022/3/26.
*/
public class Md5Util
{
/**
* Get salt string.
*
* @param n the n
* @return the string
*/
public static String getSalt(int n){
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+".toCharArray();
int length = chars.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++){
char c = chars[new Random().nextInt(length)];
sb.append(c);
}
return sb.toString();
}
}

@ -0,0 +1,30 @@
package com.peteralbus.util;
import java.util.HashSet;
import java.util.Set;
/**
* The type Type util.
* @author PeterAlbus
* Created on 2022/3/26.
*/
public class TypeUtil
{
static public boolean isImg(String type)
{
final Set<String> allowTypes = new HashSet<String>(){{
add(".jpg");
add(".jpeg");
add(".png");
add(".JPG");
add(".JPEG");
add(".PNG");
add(".webp");
add(".tif");
add(".WEBP");
add(".TIF");
}};
return allowTypes.contains(type);
}
}
Loading…
Cancel
Save