新增用户注册/登录

This commit is contained in:
2018-01-08 12:49:07 +08:00
parent 4c7a0d6e91
commit 84b81cf0ac
33 changed files with 1358 additions and 72 deletions

View File

@@ -27,6 +27,7 @@ public class DbMap {
// Composite Primary Key order: tid,cate,attr
arp.addMapping("dyna_attr", "tid,cate,attr", DynaAttr.class);
arp.addMapping("user", "userId", User.class);
arp.addMapping("user_pwd", "userId", UserPwd.class);
}
public static void addSqlTemplate(ActiveRecordPlugin arp) {

View File

@@ -1,6 +1,9 @@
package com.lxyer.config;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.config.*;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
@@ -57,7 +60,14 @@ public class FlyConfig extends JFinalConfig {
@Override
public void configInterceptor(Interceptors me) {
me.add(new LoginInterceptor());
me.add(new Interceptor() {
@Override
public void intercept(Invocation inv) {
Controller controller = inv.getController();
controller.setAttr("mine", controller.getSessionAttr("user"));
inv.invoke();
}
});
}
@Override

View File

@@ -1,5 +1,9 @@
package com.lxyer.config;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
/**
@@ -30,4 +34,20 @@ public final class LxyKit {
return new SimpleDateFormat("yyyy-MM-dd").format(time);
}
public static String md5IfNeed(String password){
if (password == null || password.isEmpty()) return "";
if (password.length() == 32) return password;
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] bytes = password.trim().getBytes();
bytes = md5.digest(bytes);
return HexBin.encode(bytes);
}
}

View File

@@ -0,0 +1,26 @@
package com.lxyer.config;
/**
* Created by JUECHENG at 2018/1/7 23:45.
*/
public class MyException extends RuntimeException {
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(Throwable cause) {
super(cause);
}
protected MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@@ -12,6 +12,8 @@ public class UrlHandler extends Handler {
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
if (target.endsWith(".html")) target = target.replace(".html", "");
next.handle(target, request, response, isHandled);
}
}

View File

@@ -2,6 +2,11 @@ package com.lxyer.config.interceptor;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.lxyer.model.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by JUECHENG at 2018/1/7 11:22.
@@ -9,6 +14,20 @@ import com.jfinal.aop.Invocation;
public class LoginInterceptor implements Interceptor {
@Override
public void intercept(Invocation inv) {
inv.invoke();
Controller controller = inv.getController();
HttpServletRequest request = controller.getRequest();
HttpServletResponse response = controller.getResponse();
User user = controller.getSessionAttr("user");
if (user == null){
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
}else {
controller.render("/user/login.html");
}
}else {
inv.invoke();
}
}
}

View File

@@ -2,6 +2,7 @@ package com.lxyer.config.route;
import com.jfinal.config.Routes;
import com.lxyer.controller.HomeController;
import com.lxyer.controller.JieController;
import com.lxyer.controller.UserController;
/**
@@ -14,5 +15,6 @@ public class SiteRoute extends Routes {
add("/", HomeController.class);
add("/user", UserController.class);
add("/jie", JieController.class);
}
}

View File

@@ -1,9 +0,0 @@
package com.lxyer.controller;
/**
* Created by JUECHENG at 2018/1/7 16:48.
*/
public class ContentController extends IController{
}

View File

@@ -58,25 +58,5 @@ public class HomeController extends IController {
render("jie/index.html");
}
/**
* 帖子详情
*/
public void jie(){
int contentId = getParaToInt(0);
//ContentInfo content = contentService.contentInfo(sessionid, contentid);
//Sheet<CommentInfo> comments = commentService.commentQuery(request.getSessionid(false) ,contentid, new Flipper().limit(30));
Record content = Content.dao.findFirst(Kv.by("contentId", contentId));
//热议
List<Content> hotReply = Content.dao.findPage(1, 8, Kv.by("order", "replyNum DESC")).getList();
setAttr("bean", content);
setAttr("hotReply", hotReply);
render("jie/detail.html");
}
}

View File

@@ -6,6 +6,7 @@ import com.jfinal.plugin.activerecord.*;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lxyer.config.E;
import com.lxyer.model.User;
import java.util.ArrayList;
import java.util.HashMap;
@@ -19,6 +20,22 @@ public class IController extends Controller {
public static final Cache cache = Redis.use();
public void index(){
String para = getPara(0, "index");
render(para + ".html");
}
public Integer getUserId() {
User user = getUser();
return user == null ? null : user.getUserId();
}
public User getUser(){
return getSessionAttr("user");
}
public Kv getParams(String... key) {
Kv kv = Kv.create();
for (String k : key) {

View File

@@ -0,0 +1,62 @@
package com.lxyer.controller;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.lxyer.config.JsonBean;
import com.lxyer.config.interceptor.LoginInterceptor;
import com.lxyer.model.Content;
import com.lxyer.service.ContentService;
import java.util.List;
/**
* Created by JUECHENG at 2018/1/7 16:48.
*/
public class JieController extends IController{
private ContentService contentService = ContentService.me;
private int userId;
/**
* 帖子详情
*/
public void index(){
int contentId = getParaToInt(0);
//ContentInfo content = contentService.contentInfo(sessionid, contentid);
//Sheet<CommentInfo> comments = commentService.commentQuery(request.getSessionid(false) ,contentid, new Flipper().limit(30));
Content content = Content.dao.findFirst(Kv.by("contentId", contentId));
//热议
List<Content> hotReply = Content.dao.findPage(1, 8, Kv.by("order", "replyNum DESC")).getList();
setAttr("bean", content);
setAttr("hotReply", hotReply);
render("detail.html");
}
/**
* 添加/修改帖子
*/
@Before(LoginInterceptor.class)
public void add(){
setAttr("bean", Content.dao.findById(getParaToInt()));
render("add.html");
}
/**
* 帖子保存
*/
@Before(LoginInterceptor.class)
public void save() {
Content content = getModel(Content.class);
contentService.save(content, getUserId());
renderJson(JsonBean.success());
}
}

View File

@@ -1,28 +1,88 @@
package com.lxyer.controller;
import com.lxyer.config.JsonBean;
import com.lxyer.model.User;
import com.lxyer.service.UserService;
/**
* Created by JUECHENG at 2018/1/7 16:40.
*/
public class UserController extends IController {
private UserService userService = UserService.me;
/**
* 注册
*/
public void create(){
JsonBean bean = new JsonBean(1);
String email = getPara("email");
String pwd = getPara("pwd");
String nickname = getPara("nickname");
try {
userService.create(email, pwd, nickname);
} catch (Exception e) {
bean.setCode(-1, e.getMessage());
}
renderJson(bean);
}
/**
* 登录
*/
public void login(){
String para = getPara();
if (para == null) {
render("login.html");
return;
}else if ("out".equals(para)){
removeSessionAttr("user");
renderJson(JsonBean.success());
return;
}
JsonBean bean = new JsonBean(1);
String username = getPara("username");
String pwd = getPara("pwd");
try {
User user = userService.login(username, pwd);
/*未来源app端
String token = userService.updateToken(user);
bean.set("user", user);
bean.set("token", token);*/
setSessionAttr("user", user);
} catch (Exception e) {
e.printStackTrace();
bean.setCode(-1, e.getMessage());
}
renderJson(bean);
}
/**
* 修改
* todo:用户修改资料
*/
public void update(){
}
/**
* 修改密码
*/
public void repwd(){
JsonBean bean = new JsonBean(1);
String pwd = getPara("pwd");
try {
userService.updatePwd(getUserId(), pwd);
} catch (Exception e) {
bean.setCode(-1, e.getMessage());
}
renderJson(bean);
}
}

View File

@@ -13,4 +13,9 @@ public class Content extends BaseContent<Content> {
public String sqlSpace() {
return "content";
}
@Override
public Content getDao() {
return dao;
}
}

View File

@@ -13,4 +13,9 @@ public class User extends BaseUser<User> {
public String sqlSpace() {
return "user";
}
@Override
public User getDao() {
return dao;
}
}

View File

@@ -0,0 +1,28 @@
package com.lxyer.model;
import com.lxyer.config.LxyKit;
import com.lxyer.model.base.BaseUserPwd;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class UserPwd extends BaseUserPwd<UserPwd> {
public static final UserPwd dao = new UserPwd().dao();
@Override
public boolean save() {
setUpdateTime(System.currentTimeMillis());
setPwd(LxyKit.md5IfNeed(getPwd()));
if (findById(getUserId()) == null) {
return super.save();
}else {
return super.update();
}
}
@Override
public boolean update() {
return save();
}
}

View File

@@ -32,12 +32,13 @@ public class _Generator {
* 部分功能使用 Db + Record 模式实现,无需生成 model 的 table 在此配置
*/
private static String[] excludedTable = {
/*"comment",
"comment",
"content",
"content_item",
"dyna_attr",
"tree",
"user"*/
"act_log",
"user",
"user_pwd"
};
/**

View File

@@ -25,14 +25,6 @@ public abstract class BaseUser<M extends BaseUser<M>> extends Model<M> implement
return getStr("username");
}
public void setPassword(java.lang.String password) {
set("password", password);
}
public java.lang.String getPassword() {
return getStr("password");
}
public void setSex(java.lang.Integer sex) {
set("sex", sex);
}

View File

@@ -0,0 +1,36 @@
package com.lxyer.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseUserPwd<M extends BaseUserPwd<M>> extends Model<M> implements IBean {
public void setUserId(java.lang.Integer userId) {
set("userId", userId);
}
public java.lang.Integer getUserId() {
return getInt("userId");
}
public void setPwd(java.lang.String pwd) {
set("pwd", pwd);
}
public java.lang.String getPwd() {
return getStr("pwd");
}
public void setUpdateTime(java.lang.Long updateTime) {
set("updateTime", updateTime);
}
public java.lang.Long getUpdateTime() {
return getLong("updateTime");
}
}

View File

@@ -1,36 +1,33 @@
package com.lxyer.model.base;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.*;
import java.util.List;
/**
* Created by JUECHENG at 2018/1/7 16:52.
*/
public interface IModel<M extends IModel<M>> {
public interface IModel<M extends Model<M>> {
String sqlSpace();
M getDao();
default List<M> findList(Kv kv){
SqlPara sqlPara = Db.getSqlPara(sqlSpace()+".list", kv);
SqlPara sqlPara = getDao().getSqlPara(sqlSpace()+".list", kv);
return (List) Db.find(sqlPara);
return getDao().find(sqlPara);
}
default Record findFirst(Kv kv){
default M findFirst(Kv kv){
SqlPara sqlPara = Db.getSqlPara(sqlSpace()+".list", kv);
return Db.findFirst(sqlPara);
return getDao().findFirst(sqlPara);
}
default Page<M> findPage(int pn, int ps, Kv kv){
SqlPara sqlPara = Db.getSqlPara(sqlSpace()+".list", kv);
return (Page) Db.paginate(pn, ps, sqlPara);
return getDao().paginate(pn, ps, sqlPara);
}
}

View File

@@ -1,9 +1,19 @@
package com.lxyer.service;
/**
import com.lxyer.model.Content; /**
* Created by JUECHENG at 2018/1/7 16:49.
*/
public class ContentService {
public static final ContentService me = new ContentService();
public void save(Content content, int userId) {
if (content.getContentId() == null) {
content.setCreateTime(System.currentTimeMillis());
content.setUserId(userId);
content.save();
}else {
content.update();
}
}
}

View File

@@ -0,0 +1,84 @@
package com.lxyer.service;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.lxyer.config.LxyKit;
import com.lxyer.model.User;
import com.lxyer.model.UserPwd;
import java.util.Random;
/**
* Created by JUECHENG at 2018/1/7 22:59.
*/
public class UserService {
public static final UserService me = new UserService();
/**
* 创建用户
* @param email
* @param pwd
* @param nickname
* @throws Exception
*/
public void create(String email, String pwd, String nickname) throws Exception {
if (StrKit.isBlank(email))
throw new Exception("注册失败,邮箱格式不正确");
if (StrKit.isBlank(pwd))
throw new Exception("注册失败,密码格式不正确");
if (User.dao.findFirst(Kv.by("email", email)) != null)
throw new Exception("注册失败,邮箱被占用");
User user = new User();
user.setUsername(email);
user.setEmail(email);
user.setNickname(nickname);
user.setAvatar("/res/images/avatar/"+ new Random().nextInt(21) +".jpg");//默认头像
user.setCreateTime(System.currentTimeMillis());
user.setStatus(1);
user.save();
UserPwd userPwd = new UserPwd();
userPwd.setUserId(user.getUserId());
userPwd.setPwd(pwd);
userPwd.save();
}
public User login(String username, String pwd) throws Exception {
User user = User.dao.findFirst(Kv.by("username", username));
if (user == null){
throw new Exception("密码错误!");
}
UserPwd userPwd = UserPwd.dao.findById(user.getUserId());
if (userPwd == null || !LxyKit.md5IfNeed(pwd).equalsIgnoreCase(userPwd.getPwd())){
throw new Exception("密码错误!");
}
if (user.getInt("status") == -1){
throw new Exception("限制登录");
}
return user;
}
public String updateToken(User user) {
return null;
}
/**
* 修改密码
* @param userId
* @param pwd
*/
public void updatePwd(Integer userId, String pwd) throws Exception {
if (StrKit.isBlank(pwd))
throw new Exception("操作失败,密码格式不正确");
UserPwd userPwd = new UserPwd();
userPwd.setUserId(userId);
userPwd.setPwd(pwd);
userPwd.update();
}
}